1

我需要在 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 = []   

有什么建议吗?我似乎无法得到它。谢谢!乙

4

3 回答 3

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]
于 2013-08-21T16:07:32.847 回答
1

看到这个问题。

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)]

(见约翰的解决方案)

于 2013-08-21T16:10:40.537 回答
-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

但是请注意,这是不可取的

于 2013-08-21T16:10:53.643 回答