0

I have two lists of lists I want to iterate through them and compare the values in each bracket on the list bracket by bracket.....

List_1
[[42, 43, 45, 48, 155, 157], [37, 330, 43, 47, 157], [258, 419, 39, 40, 330, 47], [419, 39, 44, 589, 599, 188].....
List_2
[[37, 330, 43, 47, 157], [258, 419, 39, 40, 330, 47], [419, 39, 44, 589, 599, 188], [41, 44, 526, 602, 379, 188]....

I need to compare the first bracket in List_1 [42, 43, 45, 48, 155, 157] With the first bracket in List_2 [37, 330, 43, 47, 157] the desired result is the numbers that are the same in each sequential bracket...for first bracket the result is 43 and 157

then I need to continue second bracket in List_1, with the second bracket in List_2 etc.

  • Number of values in each bracket may vary
  • I need each bracket in 1 list to compare with the corresponding bracket from the other list
  • I don't need the results to be separate

I'm at a very basic level but, I've tried a few different things including using sets intersection, list matches. I'm sure that there is a simple way but only just getting started.

    set_x = set([i[1] for i in list_1])
    print(set_x)
    set_y = set([i[0] for i in list_2])
    matches = set_x.intersection(set_y)
    print(matches)

this is providing an answer that is way off {3, 8, 396, 12,} and I can't really work out what it's doing.

also tried this

    common_elements=[]
    import itertools 
    for i in list(itertools.product(coords_list_1,coords_list_2)):
        if i[0] == i[1]:
            common_elements.append(i[0])
            print(common_elements)

but it produces a mass of results.

Thanks for your help!

2 Answers 2

1

Use zip and set's intersection:

for x, y in zip(List_1, List_2):
    print(set(x).intersection(y))

# {43, 157}
# {330, 47}
# {419, 39}
# {188, 44}
Sign up to request clarification or add additional context in comments.

Comments

1

Your approach tackles the elements in the wrong "axis". For instance:

set_x = set([i[1] for i in list_1])

creates a set of the 2nd element of each list.

In those cases, you have to forget about the indexes.

you just want to zip sublists together to perform intersection between them

List_1 = [[42, 43, 45, 48, 155, 157], [37, 330, 43, 47, 157], [258, 419, 39, 40, 330, 47], [419, 39, 44, 589, 599, 188]]
List_2 = [[37, 330, 43, 47, 157], [258, 419, 39, 40, 330, 47], [419, 39, 44, 589, 599, 188], [41, 44, 526, 602, 379, 188]]

result = [set(x) & set(y) for x,y in zip(List_1,List_2)]

result:

>>> result
[{43, 157}, {330, 47}, {419, 39}, {188, 44}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.