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

[Güncelleme] bir şey eksik, gerçekten product(a,b,c,...) yazma, yapıların yani arbirtary miktarda for x in a for y in b for z in c ... varsa ilgili hantal şeydir. Yukarıdaki örnekte d gibi bir liste listeniz olduğunu varsayalım. Onu daha kolay anlayabilir misin? Python, **b ile sözlük değerlendirme ve *a ile unpacking yapalım, ancak bu sadece bir gösterimdir. Bu gibi canavarların keyfi uzunlukta ve basitleştirilmesi için iç içe geçmişler, daha fazla araştırma için here numaralı SO'nın ötesindedir. Başlıktaki sorunun açık uçlu olduğunu vurgulamak istiyorum, bu yüzden bir sorumu kabul edersem yanlış yönlendirilmemelisin!Sırasıyla, "un için c içinde y için ..." için sırasını kullanarak nasıl basitleştirebilirim?

+0

@HH, ben ilave etmek istiyorum gibi

Eğer şeylerin bir demet ürünü kullanabilirsiniz benim cevap ver. 'ürün (* d)' ürüne eşdeğerdir (a, b, c) ' –

cevap

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

düzenlemeyi deneyin: Ayrıca

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

bu

>>> 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#'] 
İlgili konular