Home > Blockchain >  how can I open (or create) list_{i}=[]
how can I open (or create) list_{i}=[]

Time:11-15

I have a bunch of lists names that vary slightly. And rather than writing the code that manipulates these lists multiple times, how can I input the name of the list to open? so: (and the following IS NOT code:)

list1: txt_masterlist=[]
list2: img_masterlist=[]
list3: png_masterlist=[]
list4: vid_masterlist=[]

etc...

for example, to find the cardinality of lists 1-4 i'd need: len(img_masterlist) but 4x for each uniquely named list. I could use a def with a .split('_')[1] to return the 2nd part of the name, but id how to call, a list. Hope this makes sense, really what I'm asking is how to return fstring as a variable name, and call this variable in code.

Because then I could create list{i}.

CodePudding user response:

You should never get a user to provide input which should then be matched to variable names (like the names of list variables). If you need data in a data structure where a specific element should be selected based on user input, use a dictionary instead, so that you can access the appropriate list in the dictionary by using the user input as a key.

Something like:

masterlists = {'txt': [], 'img': [], 'png': [], 'vid': []}

val = input('Enter a value to add: ')
list_name = input('Enter a list to add it to: ')

masterlists[list_name].append(val)

print(masterlists)

Example run:

Enter a value to add: myfile.csv
Enter a list to add it to: txt
{'txt': ['myfile.csv'], 'img': [], 'png': [], 'vid': []}

Note that this doesn't take into account what should happen if the user enters a list name that doesn't exist yet, etc. But the basic principle should be clear.

CodePudding user response:

Global names are stored in a dictionary that is returned by globals() function. So this works:

name = "my_list"
globals()[name] = [1, 2, 3]
print(my_list) # [1, 2, 3]
```
  • Related