2011-01-06 16 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 जैसी सूचियों की एक सूची है। क्या आप इसे आसान बना सकते हैं? पाइथन हमें unpacking*a के साथ सूचियों और **b के साथ शब्दकोश मूल्यांकन के साथ करते हैं, लेकिन यह केवल संकेत है।के लिए आगे के शोध के लिए, इस तरह के राक्षसों के मनमाना-लंबाई और सरलीकरण के लिए घिरे हुए एसओ से परे है। मैं इस बात पर जोर देना चाहता हूं कि शीर्षक में समस्या खुली है, इसलिए अगर मैं कोई प्रश्न स्वीकार करता हूं तो गुमराह मत बनो!मैं बिना किसी के साथ "ज़ेड इन सी के लिए x में एक के लिए x में" के लिए कैसे सरल बना सकता हूं?

+0

@HH, मैं करने के लिए जोड़ा करने के लिए अपने उत्तर उदाहरण 'उत्पाद (* डी)' 'उत्पाद (ए, बी, सी)' के बराबर है –

उत्तर

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

 संबंधित मुद्दे

  • कोई संबंधित समस्या नहीं^_^