简体   繁体   中英

compare few elements in list of tuples

I have two list of tuples like shown in following order:

a = [(18, 299, 70, 33), (18, 323, 70, 34), 
(18, 448, 70, 35), (18, 548, 70, 36), (18, 613, 70, 37)]

b = [(18, 223, 70, 37), (18, 299, 70, 38), 
(18, 323, 70, 39), (18, 448, 70, 40), (18, 548, 70, 41), (18, 613, 70, 42)]

What I want:

1). I am trying to print elements which are in b but not in a

2). I want to compare the above shown lists in such a manner that only first three elements of individual tuples are compared irrespective of non-matching last element of that tuple ie 37 , 38 , 39 .... So in above case I want my answer to look like:

result = [(18,223,70,37)]

So as you can see in this case the algorithm would totally ignore the last number or 4th element while comparing individual tuples. Hence I want that if the first three elements of tuples are matched then it can predict that there is no difference even though fourth element may or may not be same.

What I tried:

Apart from searching solutions I just wanted to try set(b_value)-set(a_value) approach. But I knew it wont work as the result generated by this looks like this:

set([(18, 613, 70, 42), (18, 448, 70, 40), (18, 548, 70, 41), (18, 299, 70, 38), (18, 323, 70, 39), (18, 223, 70, 37)])

This is pretty obvious result as the last element of all the tuples are not matching hence this method predicts all such tuples as unmatched.

EDIT: I would like to retain the value of 4th element in my result, so deleting all 4th element in all tuples and comparing is not an option.

Produce a set for the first list containing the tuples without the last element; you can do a second loop over b to collect those whose first elements are not in the set:

a_set = {t[:-1] for t in a}
result = [t for t in b if t[:-1] not in a_set]

Algorithmically speaking, this does the same amount of work as converting both to sets and producing a set difference.

Demo:

>>> a = [(18, 299, 70, 33), (18, 323, 70, 34), 
... (18, 448, 70, 35), (18, 548, 70, 36), (18, 613, 70, 37)]
>>> b = [(18, 223, 70, 37), (18, 299, 70, 38), 
... (18, 323, 70, 39), (18, 448, 70, 40), (18, 548, 70, 41), (18, 613, 70, 42)]
>>> a_set = {t[:-1] for t in a}
>>> [t for t in b if t[:-1] not in a_set]
[(18, 223, 70, 37)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM