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

[업데이트] 일이없는, 당신이 정말로 product(a,b,c,...)를 작성, 구조 즉 arbirtary 양을 for x in a for y in b for z in c ...이있는 경우에 대한 성가신 것입니다. 위의 예에서 d과 같은 목록의 목록이 있다고 가정합니다. 좀 더 간단하게 할 수 있습니까? 파이썬은 목록을 위해서는 unpacking*a으로하고 **b을 사용하여 사전 평가를합시다. 단지 표기법입니다. 임의의 길이와 그러한 몬스터의 단순화를위한 중첩 된 for-loops는 SO를 넘어서고, 이후 연구를 위해 here. 나는 제목에있는 문제가 끝이 없다는 것을 강조하고 싶다. 그래서 내가 질문을 받아들이면 오해하지 마라."for a in y for b for z in c ..."를 순서없이 단순화하려면 어떻게해야합니까?

+0

@HH, 내가 추가하고 싶은처럼

당신이 일의 무리에 제품을 사용할 수를 내 대답 예. 'product (* d)'는'product (a, b, c)'와 동일하다. –

답변

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