Reputation: 79
I'm struggling with this code not outputing what I'm expecting.
Here the code:
'base' is a list of sets
'items' is a list of str
base = [{'🌭', '🍔'},{'🌭', '🍕'},{'🌮', '🍔'},{'🌮', '🍕'},{'🍆', '🍑'}]
items = ['🌭','🍔','🍕','🌮','🍆','🍑']
for i in items:
for j in base:
j.add(i)
My result is this if I print base
[{'🌭', '🌮', '🍆', '🍑', '🍔', '🍕'},
{'🌭', '🌮', '🍆', '🍑', '🍔', '🍕'},
{'🌭', '🌮', '🍆', '🍑', '🍔', '🍕'},
{'🌭', '🌮', '🍆', '🍑', '🍔', '🍕'},
{'🌭', '🌮', '🍆', '🍑', '🍔', '🍕'}]
But I'm looking to have something like this, where every item on items gets added to every set in base.
[{'🌭', '🌭', '🍔'},
{'🍔', '🌭', '🍔'},
{'🍕', '🌭', '🍔'},
{'🌮', '🌭', '🍔'},
{'🍆', '🌭', '🍔'},
{'🍑', '🌭', '🍔'},
{'🌭', '🌭', '🍕'},
{'🍔', '🌭', '🍕'},
{'🍕', '🌭', '🍕'},
{'🌮', '🌭', '🍕'},
{'🍆', '🌭', '🍕'},
{'🍑', '🌭', '🍕'},
...]
Upvotes: 0
Views: 519
Reputation: 26
You won't get what you need with sets, which don't allow you to repeat items. Convert it to list, and then flip the loop:
base = [{'🌭', '🍔'},{'🌭', '🍕'},{'🌮', '🍔'},{'🌮', '🍕'},{'🍆', '🍑'}]
items = ['🌭','🍔','🍕','🌮','🍆','🍑']
base2 = []
for i in base:
for j in items:
k = list(i).copy()
k.append(j)
base2.append(k)
base2
Upvotes: 1