2011-01-06 4 views
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])]) 

[Mise à jour] Une chose qui manque, que dire si vous avez vraiment for x in a for y in b for z in c ..., à savoir des structures arbirtary quantité, écriture product(a,b,c,...) est lourd. Supposons que vous ayez une liste de listes telles que d dans l'exemple ci-dessus. Pouvez-vous l'obtenir plus simple? Python laissez-nous faire unpacking avec *a pour les listes et l'évaluation du dictionnaire avec **b mais c'est juste la notation. Les boucles for-nées de longueur arbitraire et la simplification de tels monstres est au-delà de SO, pour d'autres recherches here. Je tiens à souligner que le problème dans le titre est ouvert, alors ne vous trompez pas si j'accepte une question!Comment simplifier "pour x dans a pour y dans b pour z dans c ..." avec les non ordonnés?

+0

@HH, j'ai ajouté à mon répondre par exemple 'product (* d)' est équivalent à 'product (a, b, c)' –

Répondre

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#'] 

modifier:

vous pouvez utiliser le produit sur un tas de choses comme vous voulez aussi

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

Essayez cette

>>> 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#'] 
Questions connexes