0

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.


[{'🌭', '🌭', '🍔'},
 {'🍔', '🌭', '🍔'},
 {'🍕', '🌭', '🍔'},
 {'🌮', '🌭', '🍔'},
 {'🍆', '🌭', '🍔'},
 {'🍑', '🌭', '🍔'},
 {'🌭', '🌭', '🍕'},
 {'🍔', '🌭', '🍕'},
 {'🍕', '🌭', '🍕'},
 {'🌮', '🌭', '🍕'},
 {'🍆', '🌭', '🍕'},
 {'🍑', '🌭', '🍕'},
...]
3
  • 4
    Duplicate items connot be in set! Commented Apr 7, 2020 at 14:52
  • Try to change base to List of lists Commented Apr 7, 2020 at 14:52
  • 1
    I don't understand the question. You say you want "every item on items gets added to every set in base", and isn't that exactly what happened? You have five base sets, and they each ended up containing every item. Commented Apr 7, 2020 at 14:58

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.