用for循环创建20个空列表

2024-09-29 00:19:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要20个字母从a到t的空列表。我现在的代码是:

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

为我创建了这个:

^{pr2}$

我能用一个简单的for循环来做这个吗?? 这就是我现在所拥有的。我可以把字母a到t循环打印出来

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

输出:

    a
    b
    c
    d
    e
    ...

等等。。。在

我需要它来写剧本。我有两个空列表测试。它工作正常 但现在我要玩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()

Tags: nameintarget列表forinput字母place
3条回答

使用locals()function

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

>>> list_k
    []

使用不同的方法:

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

现在您可以通过mylist["t"]访问mylist["a"]

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

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

exec不应该被过度使用,但在这里它似乎很适合。在

相关问题 更多 >