Domanda

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

[Aggiornamento] Una cosa che manca, che dire se davvero hanno for x in a for y in b for z in c ..., cioè quantità arbirtary di strutture, scrivendo product(a,b,c,...) è ingombrante. Si supponga di avere una lista di liste, come la d nell'esempio di cui sopra. Si può ottenere più semplice? Python facciamolo unpacking con *a per le liste e la valutazione dizionario con **b ma è solo la notazione. Annidati per-loop di arbitraria lunghezza e la semplificazione di tali mostri è al di là SO, per ulteriori ricerche qui . Voglio sottolineare che il problema del titolo è a tempo indeterminato, in modo da non essere fuorviati se accetto una domanda!

È stato utile?

Soluzione

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

modifica:

è possibile utilizzare il prodotto su un mucchio di cose come si vorrebbe anche

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

Altri suggerimenti

Prova questo

>>> 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#']
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top