GLHF GLHF - 1 year ago 64
Python Question

Finding the same second elements in nested lists - recursive function

I have nested lists looks like this;

[['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']]

and goes on. How can I find the lists that have same second elements, for example

['CELTIC AMBASSASDOR', 'Warrenpoint']
['FRI SKIEN', 'Warrenpoint']

['BONAY', 'Antwerp']
['NINA', 'Antwerp']

The list is too long (I'm reading it from a .csv file) and I can't determine to search which thing exactly (eg: I can't search for 'Antwerp' to find all Antwerps because I don't know all of the texts in csv file), so I thought I need a recursive function that will search until find the all nested lists seperated by second items. Couldn't figure out how to make the recursive function, if anyone has a better solution, much appreciated.

Answer Source

There's no need to use recursion here. Create a dictionary with a key of the second element and values of the whole sublist, then create a result that only includes the matches you're interested in:

import collections
l = [['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']]
d = collections.defaultdict(list)
for item in l:

result = dict(item for item in d.items() if len(d[item[0]]) > 1)


>>> import pprint
>>> pprint.pprint(result)
{'Antwerp': [['BONAY', 'Antwerp'], ['NINA', 'Antwerp']],
 'Warrenpoint': [['CELTIC AMBASSASDOR', 'Warrenpoint'],
                 ['FRI SKIEN', 'Warrenpoint']]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download