简体   繁体   中英

Remove lists within a nested list with duplicates based on last two elements

I have a nested list like this:

my_list = [['10', 'A', 'A'], ['5', 'B', 'A'], ['2', 'B', 'B'], ['10','A','B']]

I would like to check if there is a duplicate letter in the last two positions and if there is not, print those lists.

final_list = [['5','B','A'],['10','A','B']

Finally, I would like to print the numerical value from each of these lists:

only_numbers = ['5','10']

However, I'm getting stuck at the identifying duplicates within the lists. I have found this answer Removing Duplicates from Nested List Based on First 2 Elements , but I when I tried to apply this on my example code above (and actual code), I got some lists with duplicates and some without duplicates.

seen = set() 
seen_add = seen.add
final_list = [x for x in my_list if tuple(x[-2:]) not in seen and not seen_add(tuple(x[-2:]))]

But I get:

final_list = [['10', 'A', 'A'], ['5', 'B', 'A'], ['2', 'B', 'B'], ['10', 'A', 'B']]

What am I missing?


EDIT: Fixed my personal coding attempt below so that its functions (thank you to Karl Knechtel for your explanation)

only_numbers = []
for x in my_list:  
     if not x[1] == x[2]:
         add_number.append(x[0])
print(only_numbers)

This is one approach using filter and a list comprehension

Ex:

my_list = [['10', 'A', 'A'], ['5', 'B', 'A'], ['2', 'B', 'B'], ['10','A','B']]
result = [i for i, *_ in filter(lambda x: x[-1] != x[-2], my_list)]
# OR 
# [i for i, j, k in my_list if j != k]
print(result)

Output:

['5', '10']

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