0

j我的目标是将下面列表中的项目的交集 (和)捕获k到三个单独的列表中。

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], []]]
4

2 回答 2

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], []]]

或(不寒而栗)嵌套列表理解

>>> 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], []]]
于 2013-09-29T20:22:28.767 回答
0

不要忘记集合和迭代工具。我将类型转换保留在行内以更好地展示这个想法。理想情况下,您不会为 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()
于 2013-09-29T21:02:42.350 回答