I basically have a list of list like this:
JavaScript
x
11
11
1
[['1348559717', '11'],
2
['1348559717', '15'],
3
['1348562275', '16'],
4
['1348562275', '20'],
5
['1348562284', '17'],
6
['1348562284', '18'],
7
['1348562290', '19'],
8
['1349346149', '15'],
9
['1349348467', '14'],
10
['1350001260', '17']]
11
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:
JavaScript
1
8
1
[['1348559717', '11'],
2
['1348562275', '20'],
3
['1348562284', '17'],
4
['1348562290', '19'],
5
['1349346149', '15'],
6
['1349348467', '14'],
7
['1350001260', '17']]
8
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:
JavaScript
1
22
22
1
from pprint import PrettyPrinter
2
3
lst = [['1348559717', '11'],
4
['1348559717', '15'],
5
['1348562275', '16'],
6
['1348562275', '20'],
7
['1348562284', '17'],
8
['1348562284', '18'],
9
['1348562290', '19'],
10
['1349346149', '15'],
11
['1349348467', '14'],
12
['1350001260', '17']]
13
14
id_to_num = {}
15
for id_, num in lst:
16
if id_ not in id_to_num or num == '20':
17
id_to_num[id_] = num
18
19
new_lst = [[id_, num] for id_, num in id_to_num.items()]
20
21
PrettyPrinter().pprint(new_lst)
22
Output:
JavaScript
1
8
1
[['1348559717', '11'],
2
['1348562275', '20'],
3
['1348562284', '17'],
4
['1348562290', '19'],
5
['1349346149', '15'],
6
['1349348467', '14'],
7
['1350001260', '17']]
8