Python - how to generate list of variables with new number at end

只愿长相守 提交于 2020-07-05 04:52:06

问题


What I would like to do is find a more concise way of creating variables of empty lists that will be similar to each other, with the exception of different numbers at the end.

#For example:
var1 = []
var2 = []
var3 = []
var4 = []
#...
varN = []

#with the end goal of:
var_list = [var1,var2,var3,var4, ... varN]

回答1:


Use a list comprehension:

[[] for n in range(N)]

or a simple for loop

empt_lists = []
for n in range(N):
    empt_lists.append([])

Note that [[]]*N does NOT work, it will use the same pointer for all the items!!!




回答2:


Ok...possible solution is to generate class attributes, which you can use after:

class MyClass:
    pass
myinstance = MyClass()  # if you want instance for example
setattr(myinstance, "randomname", "desiredvalue")
print myinstance.randomname  # wonderfull!

put it in the list if possible in your case!




回答3:


you can concatenate the variable assignments, if that's what you mean, you can set them all to [] var1, var2, var3 = [] did you want all the variables to be set to an empty array or to actual numbers




回答4:


Dynamic variables are considered a really bad practice. Hence, I won't be giving a solution that uses them. :)

As @GarrettLinux pointed out, you can easily make a list comprehension that will create a list of lists. You can then access those lists through indexing (i.e. lst[0], lst[1], etc.)

However, if you want those lists to be named (i.e. var1, var2, etc.), which is what I think you were going for, then you can use a defaultdict from collections.defaultdict:

from collections import defaultdict
dct = defaultdict(list)
for i in xrange(5):
    dct["var{}".format(i+1)]

Demo:

>>> dct
defaultdict(<type 'list'>, {'var5': [], 'var4': [], 'var1': [], 'var3': [], 'var2': []})
>>> dct["var1"]
[]
>>> dct["var1"].append('value')
>>> dct["var1"]
['value']
>>> dct
defaultdict(<type 'list'>, {'var5': [], 'var4': [], 'var1': ['value'], 'var3': [], 'var2': []})
>>>

As you can see, this solution closely mimics the effect of dynamic variables.




回答5:


I also had this question. I ended up making a all of my variables and the making a list with the variable names

var1 = 123456 
var2 = 123457 
list1 = [var1, var2] 
raninput = input("Words") 
if raninput not in list1: 
  print("Hi")


来源:https://stackoverflow.com/questions/19845924/python-how-to-generate-list-of-variables-with-new-number-at-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!