使用不同的变量创建多个列表

时间:2014-05-07 00:54:38

标签: python

我想创建一堆名称如下的空列表:

author1_count = []
author2_count = []
...
...

依旧......但先验我不知道需要生成多少个列表。

类似问题的答案建议在(How to create multiple (but individual) empty lists in Python?)或列表数组中创建字典。但是,我希望将值附加到列表中,如下所示:

def search_list(alist, aname):
    count = 0
    author_index = 0
    author_list = alist 
    author_name = aname
    for author in author_list:
        if author == author_name:
            author_index = author_list.index(author)+1
            count = 1
    return count, author_index

cehw_list = ["Ford, Eric", "Mustang, Jason", "BMW, James", "Mercedes, Megan"]

  author_list = []
  for author in authors:
  this_author = author.encode('ascii', 'ignore')
  author_list.append(this_author)
# Find if the author is in the authorlist

for cehw in cehw_list:
  if cehw == cehw_list[0]:
    count0, position0 = search_list(author_list, cehw)
    author1_count.append(count0)

  elif cehw == cehw_list[1]:
    count1, position1 = search_list(author_list, cehw)
    author2_count.append(count1)
...
...

知道如何创建这样的不同列表。有一种优雅的方式来做到这一点?

2 个答案:

答案 0 :(得分:2)

字典!您只需在追加值时更具体,例如

author_lists = {}

for i in range(3):
    author_lists['an'+str(i)] = []


author_lists

{'an0':[],'an1':[],'an2':[]}

author_lists['an0'].append('foo')

author_lists

{'an0':['foo'],'an1':[],'an2':[]}

答案 1 :(得分:0)

你应该能够使用字典了。

data = {}
for cehw in cehw_list:
    count0, position0 = search_list(author_list, cehw)
    # Or whatever property on cehw that has the unique identifier
    if cehw in data:
        data[cehw].append(count0)
    else:
        data[cehw] = [count0]