简体   繁体   中英

Create a list of items after every iteration in python

My goal is to capture the intersection of the items in the lists below ( j and k ) into three separate lists.

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

My attempt:

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

output:

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

Desired output:

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

Use an inner list:

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

or (shudder) a nested 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], []]]

Don't forget about sets and itertools. I left the type conversions in-line to better show the idea. Ideally you won't call set() for every combinations yielded by itertools.product(), but just as an idea:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM