0

我有以下列表:

list = [(1,info1),(2,info2),(3,info3)...]

每个信息都由一个元组列表组成

info1 = [(a1,b1,c1),(a1',b1',c1'),(a1",b1",c1")...]

对于中的每个元素list,我想要以下内容:

otherlist = [(1,(a1,b1,c1)),(1,(a1',b1',c1')),(1,(a1",b1",c1"))...]

即:前面的索引info要放在每个info元组前面

我认为这是可行的,但我无法通过简单的列表理解来实现这一点

谢谢您的帮助 :)

4

2 回答 2

5

使用嵌套列表推导:

otherlist = [[(L[0], t) for t in L[1]] for L in lst]

因此对于 中的每个元素Llst我们创建一个包含 的元组的新列表(L[0], elements of L[1])

演示:

>>> lst = [(1, [('a1', 'b1', 'c1'), ("a1'", "b1'", "c1'"), ('a1"', 'b1"', 'c1"')]), (2, [('a3', 'b3', 'c3'), ("a3'", "b3'", "c3'"), ('a3"', 'b3"', 'c3"')]), (3, [('a3', 'b3', 'c3'), ("a3'", "b3'", "c3'"), ('a3"', 'b3"', 'c3"')])]
>>> [[(L[0], t) for t in L[1]] for L in lst]
[[(1, ('a1', 'b1', 'c1')), (1, ("a1'", "b1'", "c1'")), (1, ('a1"', 'b1"', 'c1"'))], [(2, ('a3', 'b3', 'c3')), (2, ("a3'", "b3'", "c3'")), (2, ('a3"', 'b3"', 'c3"'))], [(3, ('a3', 'b3', 'c3')), (3, ("a3'", "b3'", "c3'")), (3, ('a3"', 'b3"', 'c3"'))]]
于 2013-07-22T16:44:18.060 回答
2
otherlist = [(x[0],y) for x in first_list for y in x[1]]
于 2013-07-22T16:46:06.747 回答