Use one list as search key for another list with sublist of list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Use one list as search key for another list with sublist of list (/thread-35676.html) |
Use one list as search key for another list with sublist of list - jc4d - Nov-30-2021 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? RE: Use one list as search key for another list with sublist of list - Gribouillis - Nov-30-2021 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] RE: Use one list as search key for another list with sublist of list - jc4d - Jan-10-2022 Thank you for your time and answer 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] RE: Use one list as search key for another list with sublist of list - jc4d - Jan-11-2022 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) RE: Use one list as search key for another list with sublist of list - jc4d - Jan-11-2022 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) |