6
#!/usr/bin/python
#
# Description: I try to simplify the implementation of the thing below.
# Sets, such as (a,b,c), with irrelavant order are given. The goal is to
# simplify the messy "assignment", not sure of the term, below.
#
#
# QUESTION: How can you simplify it? 
#
# >>> a=['1','2','3']
# >>> b=['bc','b']
# >>> c=['#']
# >>> print([x+y+z for x in a for y in b for z in c])
# ['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
#
# The same works with sets as well
# >>> a
# set(['a', 'c', 'b'])
# >>> b
# set(['1', '2'])
# >>> c
# set(['#'])
#
# >>> print([x+y+z for x in a for y in b for z in c])
# ['a1#', 'a2#', 'c1#', 'c2#', 'b1#', 'b2#']


#BROKEN TRIALS
d = [a,b,c]

# TRIAL 2: trying to simplify the "assignments", not sure of the term
# but see the change to the abve 
# print([x+y+z for x, y, z in zip([x,y,z], d)])

# TRIAL 3: simplifying TRIAL 2
# print([x+y+z for x, y, z in zip([x,y,z], [a,b,c])])

[Update] A thing missing, what about if you really have for x in a for y in b for z in c ..., i.e. arbirtary amount of structures, writing product(a,b,c,...) is cumbersome. Suppose you have a list of lists such as the d in the above example. Can you get it simpler? Python let us do unpacking with *a for lists and the dictionary evaluation with **b but it is just the notation. Nested for-loops of arbitrary-length and simplification of such monsters is beyond SO, for further research here. I want to stress that the problem in the title is open-ended, so do not be misguided if I accept a question!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
hhh
  • 50,788
  • 62
  • 179
  • 282
  • @HH, I added to my answer eg. `product(*d)` is equivalent to `product(a,b,c)` – John La Rooy Jan 06 '11 at 11:43
  • As asked, the question is too broad. As answered, it's a duplicate; please see https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists. – Karl Knechtel Jun 25 '22 at 00:10

2 Answers2

12

Try this

>>> import itertools
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#'] 
>>> print [ "".join(res) for res in itertools.product(a,b,c) ]
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
yanjost
  • 5,223
  • 2
  • 25
  • 28
8
>>> from itertools import product
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#']
>>> map("".join, product(a,b,c))
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']

edit:

you can use product on a bunch of things like you would like to also

>>> list_of_things = [a,b,c]
>>> map("".join, product(*list_of_things))
John La Rooy
  • 295,403
  • 53
  • 369
  • 502