Skip to content
Advertisement

Remove duplicated considering one element from a list of lists python

I basically have a list of list like this:

[['1348559717', '11'],
 ['1348559717', '15'],
 ['1348562275', '16'],
 ['1348562275', '20'],
 ['1348562284', '17'],
 ['1348562284', '18'],
 ['1348562290', '19'],
 ['1349346149', '15'],
 ['1349348467', '14'],
 ['1350001260', '17']]

I would like to remove the lists which contains duplicated values in index [0]. Also, i always need to have the list which its index [1] = ’20’, in this case ['1348562275', '20']. So my wanted list would be:

[['1348559717', '11'],
 ['1348562275', '20'],
 ['1348562284', '17'],
 ['1348562290', '19'],
 ['1349346149', '15'],
 ['1349348467', '14'],
 ['1350001260', '17']]

Does anyone have any idea how could i do it?

Advertisement

Answer

You could use a dictionary then convert it back to a list after processing:

from pprint import PrettyPrinter

lst = [['1348559717', '11'],
       ['1348559717', '15'],
       ['1348562275', '16'],
       ['1348562275', '20'],
       ['1348562284', '17'],
       ['1348562284', '18'],
       ['1348562290', '19'],
       ['1349346149', '15'],
       ['1349348467', '14'],
       ['1350001260', '17']]

id_to_num = {}
for id_, num in lst:
    if id_ not in id_to_num or num == '20':
        id_to_num[id_] = num

new_lst = [[id_, num] for id_, num in id_to_num.items()]

PrettyPrinter().pprint(new_lst)

Output:

[['1348559717', '11'],
 ['1348562275', '20'],
 ['1348562284', '17'],
 ['1348562290', '19'],
 ['1349346149', '15'],
 ['1349348467', '14'],
 ['1350001260', '17']]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement