Tiger1
Tiger1

Reputation: 1377

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

Upvotes: 0

Views: 88

Answers (2)

bcollins
bcollins

Reputation: 3459

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

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

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

Upvotes: 2

Related Questions