5

我在字典中有列表:

Number_of_lists=3           #user sets this value, can be any positive integer
My_list={}
for j in range(1,Number_of_lists+1):
  My_list[j]=[(x,y,z)]  

Number_of_lists是用户设置的变量。在事先不知道用户设置的值的情况下,我希望最终获得所有字典列表的合并列表。例如,如果Number_of_lists=3和对应的列表是My_list[1]=[(1,2,3)], My_list[2]=[(4,5,6)]My_list[3]=[(7,8,9)]则结果将是:

All_my_lists=My_list[1]+My_list[2]+My_list[3]

其中: All_my_lists=[(1,2,3),(4,5,6),(7,8,9)].

所以我想做的是尽可能地自动化上述过程:

Number_of_lists=n #where n can be any positive integer

到目前为止,我有点迷失了,试图使用迭代器来添加列表并且总是失败。我是 python 初学者,这是我的一个爱好,所以如果你回答,请在你的回答中解释所有内容,我这样做是为了学习,我不是要求你做我的作业:)

编辑

@codebox(请看下面的评论)正确地指出,My_List我的代码中显示的实际上是字典而不是列表。如果您使用任何代码,请小心。

4

4 回答 4

1

如果您只关心最终列表,并且实际上并不需要My_list(您应该重命名,因为它是一本字典!),那么您可以这样做:

Number_of_lists=3
result = []
for j in range(1,Number_of_lists+1):
    result += (x,y,z)
于 2012-08-15T10:47:27.983 回答
1

使用列表理解:

>>> Number_of_lists=3 
>>> My_list={}
>>> for j in range(1,Number_of_lists+1):
      My_list[j]=(j,j,j)
>>> All_my_lists=[My_list[x] for x in My_list]

>>> print(All_my_lists)
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

All_my_lists=[My_list[x] for x in My_list]相当于:

All_my_lists=[]
for key in My_list:
   All_my_lists.append(My_list[key])
于 2012-08-15T10:48:20.900 回答
1

All_my_lists先生成然后再生成可能更容易My_list

建造All_my_lists

使用列表理解range()生成All_my_lists

>>> num = 3  # for brevity, I changed Number_of_lists to num
>>> All_my_lists = [tuple(range(num*i + 1, num*(i+1) + 1)) for i in range(0, num)]
>>> All_my_lists
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

或者,我们可以使用itertools 配方grouper()列表中的函数,这将产生更简洁的代码:

>>> All_my_lists = list(grouper(num, range(1, num*3+1)))
>>> All_my_lists
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

建造My_lists

然后我们可以使用dict构造函数和列表理解并enumerate()构建派生My_listAll_my_list

>>> My_lists = dict((i+1, [v]) for i,v in enumerate(All_my_lists))
>>> My_lists
{1: [(1, 2, 3)], 2: [(4, 5, 6)], 3: [(7, 8, 9)]}
>>> My_lists[1]
[(1, 2, 3)]
>>> My_lists[2]
[(4, 5, 6)]
>>> My_lists[3]
[(7, 8, 9)]
于 2012-08-15T10:56:42.390 回答
1

您可以尝试一种更实用的方法,方法是Number_of_lists使用以下命令转换为一系列键range并从字典中选择map

My_list={1:[1,2,3], 2:[4,5,6], 3:[7,8,9], 4:[10,11,12]}
Number_of_lists=3
All_my_lists=map(lambda x: tuple(My_list[x]), range(1, Number_of_lists+1))

示例输出:

>>> All_my_lists
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
于 2012-08-15T11:06:08.457 回答