We are given the following two lists of random numers:
import numpy as np
import random
random.seed(1)
first = random.sample(xrange(10), 5)
random.seed(2)
second = random.sample(xrange(10), 5)
print("first ="), first
print("second ="), second
-------------------------
first = [1, 7, 6, 9, 2]
second = [9, 8, 0, 7, 5]
of which we want to find the intersection using a line-by-line standard comparison as
loop = []
for first_element in first:
for second_element in second:
if first_element == second_element:
loop.append(first_element)
print loop
----------
[7, 9]
I wanted to make that more Pythonic with a comprehensive assignment upon conditions as
comprehension = [[first_element for second_element in second if
first_element == second_element] for first_element
in first]
print comprehension
-------------------
[[], [7], [], [9], []]
The two results are different (the last also show the un-matched results), therefore I guess there is a difference in the two assignments. The former (using a standard for...for...if
) is exactly what I want to have, yet I would like the latter approach since I have got many more of them and I want to avoid writing inner loops all the times.