Home > other >  how to make list in file and editing?
how to make list in file and editing?

Time:05-01

python code

import from file

if I have List [ ['m',1],['n',5],['t',4] ]

I want if I input m and add 3, return me ['m',4]

List [ ['m',4],['n',5],['t',4] ]

but if I input f and add 3, return me [f,3]

List [ ['m',1],['n',5],['t',4] ,['f',3] ]

This is what I do but it is wrong

 -------> main_list=[ ["m",1],["n",5],["t",4]  ]  # I want import list from file

def items_in_list(input,add):
    if any(input in sublist for sublist in main_list):
        print("we have it")
        sublist[1]=  add            #if I have "m" add 4 is mean ["m",5]


    else:
        ele = [input,add]           #if I have "f" add 4 is mean ["f",3]
        main_list.append(ele)


items=input("enter you items: ")
add=int(input("enter you add: "))
items_in_list(items,add)

print(main_list)

than storage list in the same file with editing

CodePudding user response:

Change your function to the below:

def items_in_list(item, add):
    if item in [l[0] for l in main_list]:
        return [[l[0],l[1] (add if l[0]==item else 0)] for l in main_list]
    else:
        return main_list [item,add]

>>> items_in_list("m",3)
[['m', 4], ['n', 5], ['t', 4]]

>>> items_in_list("f",3)
[['m', 1], ['n', 5], ['t', 4], 'f', 3]

CodePudding user response:

It becomes easier if you use dictionary instead of list. I will show further the solution. On line: 'if any(input in sublist for sublist in main_list):', sublist exists only in that context. Finished the loop, the variable does not exist. Sublist isn't present on line: "sublist[1]= add #if I have "m" add 4 is mean ["m",5]".

Code:

main_list=[ ["m",1],["n",5],["t",4]  ]  # I want import list from file

def items_in_list(inp,ad):
    list_dict = dict(main_list)
    # convert list into dictionary to manipulate easier

    if inp in list_dict.keys():
        list_dict[inp]  = ad
    else:
        list_dict[inp] = ad
    return [[k, v] for (k, v) in list_dict.items()]
    # return dictionary to list format

inp=input("enter you items: ")
add=int(input("enter you add: "))

print(items_in_list(inp,add))
  • Related