Pregunta

#!/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])])

[Actualización] Una cosa que falta, ¿qué pasa si realmente tiene for x in a for y in b for z in c ..., es decir, la cantidad de estructuras arbirtary, escribiendo product(a,b,c,...) es engorroso. Suponga que tiene una lista de listas, como la d en el ejemplo anterior. Se puede conseguir que sea más sencillo? Python hagamos unpacking con *a para las listas y la evaluación diccionario con **b pero es sólo la notación. Anidado para-bucles de arbitraria de longitud y simplificación de tales monstruos está más allá de SO, para la investigación adicional aquí . Quiero hacer hincapié en que el problema en el título es de composición abierta, así que no se mal guiados si acepto una pregunta!

¿Fue útil?

Solución

>>> from itertools import product
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#']
>>> map("".join, product(a,b,c))
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']

editar

Puede utilizar el producto en un montón de cosas como que le gustaría también

>>> list_of_things = [a,b,c]
>>> map("".join, product(*list_of_things))

Otros consejos

Probar

>>> 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#']
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top