我需要在python脚本中创建一个命名列表列表。
我想要做的是创建一个mklist方法,该方法将在列表中获取字符串并创建为每个字符串命名的列表。所以,从这里开始:
a = "area"
for i in range(1, 37):
x = str(a) + str("%02d" % (i,))
' '.join(x.split())
我想得到以下内容:
area01 = []
area02 = []
area03 = []
area04 = []
area05 = []
area06 = []
area07 = []
area08 = []
area09 = []
area10 = []
area11 = []
area12 = []
area13 = []
area14 = []
area15 = []
area16 = []
area17 = []
area18 = []
area19 = []
area20 = []
area21 = []
area22 = []
area23 = []
area24 = []
area25 = []
area26 = []
area27 = []
area28 = []
area29 = []
area30 = []
area31 = []
area32 = []
area33 = []
area34 = []
area35 = []
area36 = []
有什么建议吗?我似乎无法得到它。谢谢! ë
答案 0 :(得分:5)
这需要列表列表:
area = [[] for i in range(37)]
或列表的字典:
area = {i: [] for i in range(1, 37)} # Python 2.7+
area = dict((i, []) for i in range(1, 37)) # Python 2.6 or earlier
然后您可以使用以下方式访问每个项目:
area[1]
area[2]
...
area[36]
答案 1 :(得分:1)
请参阅this问题。
a = "area"
for i in range(1, 37):
x = str(a) + str("%02d" % (i,))
locals()[x] = []
如果您希望列表是全局列表,请使用globals()。
这会给你空的列表变量area01到area36。
你应该注意,只是因为它可以完成,并不意味着它应该。更好/更易读的解决方案是:
area = [[] for i in range(37)]
(见约翰的解决方案)
答案 2 :(得分:-1)
类似的东西:
a = "area"
x = [ "%s%02d = []" % (a, i) for i in range(1,37) ]
print('\n'.join(x))
如果您希望在当前Python会话中定义列表,请使用
来填充最后一行for i in range(0, 36):
exec(x[i])
并查看
print area01
print area35