简体   繁体   中英

Python - Flatten sets and tuples into one list of sets

Hoping someone can help me with this. I have a list of sets and tuples, and I want to flatten it to one list of sets.

What I have:

 [({'item1', 'item2'}, 'item_a'),
 ({'item1', 'item2'}, 'item_b'),
 ({'item2', 'item3'}, 'item_a'),
 ({'item2', 'item3'}, 'item_b')]

Desired output:

[{'item1', 'item2', 'item_a'},
 {'item1', 'item2', 'item_b'},
 {'item2', 'item3', 'item_a'},
 {'item2', 'item3', 'item_b'}]

I have tried these functions, but it doesn't work:

list_flat = [item for sublist in list for item in sublist]

and

flat_list = []
for sublist in t:
    for item in sublist:
        flat_list.append(item)

Use iterable unpacking:

>>> l1 = [
...  ({'item1', 'item2'}, 'item_a'),
...  ({'item1', 'item2'}, 'item_b'),
...  ({'item2', 'item3'}, 'item_a'),
...  ({'item2', 'item3'}, 'item_b')
... ]
>>> l2 = [{b, *a} for a, b in l]
>>> l2
[{'item2', 'item_a', 'item1'}, {'item2', 'item_b', 'item1'}, {'item2', 'item_a', 'item3'}, {'item2', 'item_b', 'item3'}]

(the nested sets are unordered)

The list comprehension uses sequence unpacking twice:

  1. to unpack the (set, string) tuples in the original list.
  2. to unpack the set to create a new set

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