Python Forum

Full Version: Use one list as search key for another list with sublist of list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have two lists that returns some vector values with it's own name:
list1 = [['orange', [1, 2, 3]]]
list2 = [['apple', [1, 2, 3]], ['banana', [1, 2, 3]], ['pear', [-1, 2, 3]], ['kiwi', [-1, -2, 3]]].

I would need to use the list1 as a "search key" and ignoring the string on the list2 and print out the sublist that are not the same than in list1, which in theory should be:
newlist = [['pear' [-1, 2, 3], ['kiwi', [-1, -2, 3]]]

Could anyone give me a light on this?
You could do
S = set(tuple(x[1]) for x in list1)
result = [x for x in list2 if tuple(x[1]) not in S]
Thank you for your time and answer Smile
I wanted to go further and then compare the first item of the vector's list only so I tried the code bellow but I get a TypeError:

S = set(tuple(x[1]) for x in list1[0])
result = [x for x in list2[0] if tuple(x[1]) not in S]
I tried disecting it but is not taking me far since eventhough it is returning the difference, the result is not "filling back" to what list it belongs, which should return
['pear', [-1, 2, 3]]
list1 = [['orange', [1, 2, 3]]]
list2 = [['apple', [1, 2, 3]], ['banana', [1, 2, 3]], ['pear', [-1, 2, 3]], ['kiwi', [1, -2, 3]]]

S = set(tuple(x[1]) for x in list1)

a = [x[1][0] for x in list1]

b = [x[1][0] for x in list2]

z = [x for x in b if x not in a]
print(z)
I got help on other site but I wanted to share the solution just in case anyone else has the same problem.

list1 = [['orange', [1, 2, 3]]]
list2 = [['apple', [1, 2, 3]], ['banana', [1, 2, 3]], ['pear', [-1, 2, 3]], ['kiwi', [1, -2, 3]]]

y = [x for x in list2 if x[1][0] not in [a[1][0] for a in list1]]
print(y)