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

[更新]一個缺少的東西,怎麼樣,如果你真的有for x in a for y in b for z in c ...,即結構arbirtary量,書寫product(a,b,c,...)很麻煩。假設您有一個列表,例如上面例子中的d。你能更簡單嗎? Python讓我們做unpacking*a列表和字典評估與**b但它只是符號。爲了進一步研究here,任意長度和簡化這些怪物的嵌套for-loops超出了SO。我想強調標題中的問題是開放式的,所以如果我接受一個問題,不要誤導!我該如何簡化「for x in a for y in b for z in c ...」與無序?

+0

@HH,我加入到我的回答例如。 `product(* d)`相當於`product(a,b,c)` – 2011-01-06 11:43:15

回答

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

編輯:

您可以使用產品上一堆東西像你想也

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

試試這個

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