简体   繁体   中英

How to group list items based on common items in python

I have below list which contains tuples :

mylist = [(0, 2), (1, 2), (1, 3)] 

As we can see from above list, item 0 (0, 2) and item 1 (1, 2) has common number 2 and item 1 (1, 2) and item 2 (1, 3) has common number 1 , so how can I create a new list or reformat the existing list such that it looks like below:

my_new_list = [(0, 1, 2), (1, 2, 3)]

mylist can have n number of items (tuples) in it.

Something like this should work. I modified mylist a bit to be more representative of the problem:

mylist = [(3, 2), (1, 2),(8,9), (1, 3),(2,4)] 
my_new_list = []
for l in mylist:
    ind = mylist.index(l)
    stub= mylist[ind+1:]
    if ind<=len(mylist)-2:
        for s in stub:
            inter = set(l).intersection(set(s))
            if len(inter)>0:
                my_new_list.append(set(l+s))
my_new_list

Edit: To convert each element of my_new_list to tuple, use:

for i in range(len(my_new_list)):
   my_new_list[i]=tuple(my_new_list[i])

Output:

[{1, 2, 3}, {1, 2, 3}, {2, 3, 4}, {1, 2, 3}, {1, 2, 4}]

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