简体   繁体   中英

List of tuples of sets to a list of sets

This is the dataset:

data=[(frozenset({'I1'}), frozenset({'I2'})), (frozenset({'I1'}), frozenset({'I3'})), (frozenset({'I1'}), frozenset({'I4'})), (frozenset({'I2'}), frozenset({'I3'})), (frozenset({'I2'}), frozenset({'I4'})), (frozenset({'I3'}), frozenset({'I4'}))]

and I want it to convert it to a list like below:

[ frozenset({'I1','I2'}), frozenset({'I1','I3'}),...]

tried convertion

data=[(frozenset({'I1'}), frozenset({'I2'})), (frozenset({'I1'}), frozenset({'I3'})), (frozenset({'I1'}), frozenset({'I4'})), (frozenset({'I2'}), frozenset({'I3'})), (frozenset({'I2'}), frozenset({'I4'})), (frozenset({'I3'}), frozenset({'I4'}))]
for x in data:
    for y in x:
        #tests

this is what I'm trying to make

[ frozenset({'I1','I2'}), frozenset({'I1','I3'}),...]

How about this?

sets_lst = [(frozenset({'I1'}), frozenset({'I2'})), (frozenset({'I1'}), frozenset({'I3'})),
                   (frozenset({'I1'}), frozenset({'I4'})), (frozenset({'I2'}), frozenset({'I3'})),
                   (frozenset({'I2'}), frozenset({'I4'})), (frozenset({'I3'}), frozenset({'I4'}))]


result_lst = [frozenset().union(*curr_set_group) for curr_set_group in sets_lst]

Let me know if anything is unclear or if you have any questions!

You want to chain together the frozenset s in each tuple, then convert each of those chains to a frozenset

from itertools import chain
result = list(map(frozenset, map(chain.from_iterable, data)))
# [frozenset({'I1', 'I2'}), frozenset({'I1', 'I3'}), frozenset({'I1', 'I4'}), frozenset({'I3', 'I2'}), frozenset({'I2', 'I4'}), frozenset({'I3', 'I4'})]

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