在python中每次迭代后创建一个项列表

时间:2013-09-29 20:15:43

标签: python

我的目标是将以下列表中的项目(jk)的交叉点捕获到三个单独的列表中。

j=[[1,2,3],[2,3,4,],[2,1,3]]
k=[[2,4,5],[3,2,1,][4,5,6]]

我的尝试:

>>> b=[]
>>> for x in j:
    for y in k:
        c=[h for h in x if h in y]
            b.append(c)

输出:

>>> b
[[2], [1, 2, 3], [], [2, 4], [2, 3], [4], [2], [2, 1, 3], []]

期望的输出:

[[[2], [1, 2, 3], []], [[2, 4], [2, 3], [4]], [[2], [2, 1, 3], []]]

2 个答案:

答案 0 :(得分:2)

使用内部列表:

>>> b = []
>>> for x in j:
...     inner = []
...     for y in k:
...         c = [h for h in x if h in y]
...         inner.append(c)
...     b.append(inner)
...
>>> b
[[[2], [1, 2, 3], []], [[2, 4], [2, 3], [4]], [[2], [2, 1, 3], []]]

或(颤抖)嵌套的list comprehension

>>> b = [[[h for h in x if h in y] for y in k] for x in j]
>>> b
[[[2], [1, 2, 3], []], [[2, 4], [2, 3], [4]], [[2], [2, 1, 3], []]]

答案 1 :(得分:0)

不要忘记集合和itertools。我在线留下了类型转换以更好地展示这个想法。理想情况下,您不会为itertools.product()产生的每个组合调用set(),但这只是一个想法:

import itertools
from collections import defaultdict

j=[[1,2,3],[2,3,4],[2,1,3]]
k=[[2,4,5],[3,2,1],[4,5,6]]

d = defaultdict(list)
for x,y in itertools.product(j,k):
    d[tuple(x)].append( list( set(x) & set(y) ) )
print d.values()