使用for循环创建20个空列表

时间:2013-06-18 08:11:24

标签: python

我需要20个空列表,其中包含a到t的字母。我现在的代码是:

    list_a = []
    list_b = []
    list_c = []
    ...

创造了我:

    list_a[]
    list_b[]
    list_c[]
    ...

我可以用一个简单的for循环以某种方式做到这一点吗? 这就是我现在所拥有的。我可以将字母从a循环到t并打印出来

    for i in range(ord('a'), ord('t') +1):
        print i

输出:

    a
    b
    c
    d
    e
    ...

依旧......

我需要它为我写的那个脚本。我有2个空列表供测试。它工作正常 。但现在我需要玩20个列表

from os import system

    list_a = []
    list_b = []
    list_c = [1, 2, 3, 4, 5]


while True:
    system("clear")

    print "\nList A ---> ", list_a
    print "List B ---> ", list_b
    print "List C ---> ", list_c

    item = input ("\n?> ")

    place = [list_a, list_b, list_c]
    place_name = ["List A", "List B", "List C"]

    for i ,a in zip(place, place_name):
        if item in i:
             print "\nItem", item, "--->", a
             print "\n\n1) List A"
             print "2) List B"
             print "3) List C\n"

             target = input("move to ---> ")
             target = target - 1
             target = place[target]

             i.remove(item)
             target.append(item)

             print "\nItem moved"

             break

     raw_input()

4 个答案:

答案 0 :(得分:5)

使用不同的方法:

mylist = {letter:[] for letter in "abcdefghijklmnopqrst"}

现在,您可以通过mylist["a"]

访问mylist["t"]

答案 1 :(得分:1)

使用locals() function

>>> names = locals()
>>> for i in xrange(ord('c'), ord('t')+1):
>>>   names['list_%c' % i] = []

>>> list_k
    []

答案 2 :(得分:1)

您可以使用exec来解释生成的代码。

for i in xrange(ord('a'),ord('t')+1):
    exec("list_%c=[]" % i)
print locals()

exec不应该被滥用,但在这里似乎很合适。

答案 3 :(得分:0)

您可以列出像my_list = [[] for i in range (20)]这样的列表。

如果你想使用for循环,即不使用python的真棒列表理解,那么你可以这样做:

my_list = []
for i in range (20):
    my_list.append ([])
相关问题