简体   繁体   中英

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 - ie 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.

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()]

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()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM