简体   繁体   中英

Python. How to find and group duplicated value in dictionry of list?

I need to find any intersection in lists and group them in a new list.

I have a dictionary for example:

my_dict = {A:[1, 5], B:[1, 3], C:[0, 5], D:[4, 7], E:[9, 8]} 

new_list = [A, B, C]
or the dict
new_dict = [A:[1, 5], B:[1, 3], C:[0, 5]]

explanation of this A B and C have intersected value in 1 and 5.

Here is how you can list all possible intersections:

my_dict = {'A':[1, 5], 'B':[1, 3], 'C':[0, 5], 'D':[4, 7]}
new_list = []

for k in my_dict:
    c = [k]
    for l in my_dict:
        if k!=l:
            if any(a==b for a in my_dict[k] for b in my_dict[l]):
                c.append(l)
    if len(c) > 1:
        new_list.append(c)

print(new_list)

Output:

[['A', 'B', 'C'], ['B', 'A'], ['C', 'A']]

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