Jwem93
Jwem93

Reputation: 267

How to return unique values from list of pairs?

I have a list of pairs given as:

a = [[0, 1], [1, 3], [2, 1], [3, 1]]

I would like to return unique matches as a new list for all numbers inside 'a'. As an example, I'd like to create something like below - i.e. where I can select any number from 'a' and see all other numbers associated with it from all of the pairs. The list of lists, b, below is an example of what I'd like to achieve:

b = [ [0,[1]] , [1,[0,2,3]] , [2,[1]] , [3,[1]] ]

I am open to more efficient/better ways of displaying this. The example above is just one way that came to mind.

Upvotes: 0

Views: 204

Answers (2)

Olvin Roght
Olvin Roght

Reputation: 7812

In case if your list contains lists with different length:

from collections import defaultdict

a = [[0, 1], [1, 3], [2, 1], [3, 1]]
b = defaultdict(set)
for items in a:
    for item in items:
        b[item] |= set(items) ^ {item}

To get exact output you ask for use:

c = [[key, list(value)] for key, value in b.items()]

Upvotes: 0

Nullman
Nullman

Reputation: 4279

from collections import defaultdict

a = [[0, 1], [1, 3], [2, 1], [3, 1]]
c = defaultdict(set) # default dicts let you manipulate keys as if they already exist
for item in [[0, 1], [1, 3], [2, 1], [3, 1]]:
    # using sets avoids duplicates easily
    c[item[0]].update([item[1]])
    c[item[1]].update([item[0]])
# turn the sets into lists
b = [[item[0], list(item[1])] for item in c.items()]

Upvotes: 1

Related Questions