Home > Mobile >  List comprehension with Set comprehension in Python
List comprehension with Set comprehension in Python

Time:05-19

I have a list of list which contains set in them, what I want is list of list with a single set item.

i.e. ["item1", "item2", {1,2,3,4}, "item4"] --> [["item1", "item2", 1, "item4"],["item1", "item2", 2, "item4"],["item1", "item2", 3, "item4"],["item1", "item2", 4, "item4"]]

Any idea how can I achieve this?

CodePudding user response:

Assuming you only have a single set you need to expand in this way and it always sits at index 2 in the original list:

data = ["item1", "item2", {1, 2, 3, 4}, "item4"]

result = [data[:2]   [x]   data[3:] for x in data[2]]
print(result)

Output:

[['item1', 'item2', 1, 'item4'], ['item1', 'item2', 2, 'item4'], ['item1', 'item2', 3, 'item4'], ['item1', 'item2', 4, 'item4']]

CodePudding user response:

This is more generalized approach that the other answer,

data = ["item1", "item2", {1,2,3,4}, "item4"]
sets = list(filter(lambda item:True if type(item) == set else False, data))
list(map(data.remove, sets))
new_data = [data   [s] for set_ in sets for s in set_]

Output -

[['item1', 'item2', 'item4', 1],
 ['item1', 'item2', 'item4', 2],
 ['item1', 'item2', 'item4', 3],
 ['item1', 'item2', 'item4', 4]]
  • Related