Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two lists and printing the list in Python

Tags:

python

list

I have two lists Z1 and Z2. I am comparing these two lists and if at least one sublist of Z1 appears in Z2, I want to print full Z1. I present the current and expected output.

Z1=[[0, 4], [0, 5], [4, 5]]
Z2=[[6, 5], [4, 9], [4, 8], [5, 3], [0,4]]

for i in range(0,len(Z1)):
    if (Z1[i]==Z2[i]):
        print("Z1 =",Z1)

The current output is

(Blank)

The expected output is

Z1=[[0, 4], [0, 5], [4, 5]]
like image 387
rajunarlikar123 Avatar asked May 20 '26 10:05

rajunarlikar123


2 Answers

An rather elegant solution can be using sets and their intersection:

Z1=[[0, 4], [0, 5], [4, 5]]
Z2=[[6, 5], [4, 9], [4, 8], [5, 3], [0,4]]

zs1 = set(map(tuple, Z1))
zs2 = set(map(tuple, Z2))

if (zs1 & zs2):
    print("Z1 =",Z1)
like image 56
Michael Butscher Avatar answered May 21 '26 23:05

Michael Butscher


You are not looking over all of Z2 at most you arrive at i=2 so you never arrive at the last item in Z2 which is the one you are looking for (which should be i=4, but len(Z1) < 4).

Just loop over both, brute force solution:

>>> for z1 in Z1:
...     for z2 in Z2:
...             if z1 == z2:
...                     print("Z1 =",Z1)
...                     break
... 
Z1 = [[0, 4], [0, 5], [4, 5]]
like image 23
Nathan McCoy Avatar answered May 21 '26 23:05

Nathan McCoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!