Thomasedv - 1 year ago 60
Python Question

# List of lists, matching first item in a list to second element in the others lists

Say i got this list

``````A = [['a','b'],
['b','c'],
['c','a'],
['d','a'],
['e',None]]
``````

What's the best/efficient way to match the elements, so that you can find out which list that has a match between the first and second element in the lists.

Expected matches would be:

• list 2 and 3 matches 0

• list 1 matches list 2

• list 0 matches list 1.

As seen, there can be more that match on one list, and there can be None values that doesn't match any. There will also be other items in the list in the list, but are not needed for this example. The first and second item in each list does not match. I want to run something each time there is a match, and needed an easy way to do that.

Does that makes sense and is doable?

Create a mapping from first element to index. I'm presuming the first elements are unique to simplify this example:

``````indices = {t[0]: i for i, t in enumerate(A)}
``````

Now you can trivially map each element to an index that matches it:

``````for index, (first, second) in enumerate(A):
if second in indices:
print(f'Row {index} matches row {indices[second]}')
``````

Demo:

``````>>> A = [['a','b'],
...      ['b','c'],
...      ['c','a'],
...      ['d','a'],
...      ['e',None]]
>>> indices = {t[0]: i for i, t in enumerate(A)}
>>> for index, (first, second) in enumerate(A):
...     if second in indices:
...         print(f'Row {index} matches row {indices[second]}')
...
Row 0 matches row 1
Row 1 matches row 2
Row 2 matches row 0
Row 3 matches row 0
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download