2013-06-18 26 views
1

我需要20名空列表与来自于t.My代码现在字母创建20个空列表是:与循环

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

创建我:

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

我可以做这与一个简单的循环不知何故? 这就是我现在所拥有的。我可以循环从字母到t并打印出来

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

输出:

a 
    b 
    c 
    d 
    e 
    ... 

等等...

我需要它是剧本我wrote.I有2名testing.It的做工精细 。但空列表现在我需要用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() 
+2

您应该使用而不是创建20个不同的变量(列表或字典)列表的列表。 –

回答

5

使用打不同的方法:

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

现在,你可以通过mylist["t"]

0

访问mylist["a"]您可以作出这样my_list = [[] for i in range (20)]列表的列表。

如果你想使用一个for循环,即不使用Python的真棒列表理解,那么你可以采取以下方式:

my_list = [] 
for i in range (20): 
    my_list.append ([]) 
1

使用locals()function

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

>>> list_k 
    [] 
1

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

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

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