我有以下要求。將列表中的元素與所有可能的分隔符結合使用
我有說有3個要素[X,Y,2]
我想這樣做是產生一個分隔字符串列表(比如「 - 」)(或不能)各元素之間。數組中元素的順序應該保留。
所以輸出將是:
'XY2'
'X-Y-2'
'X-Y2'
'XY-2'
是有一種優雅的方式來這蟒蛇?
我有以下要求。將列表中的元素與所有可能的分隔符結合使用
我有說有3個要素[X,Y,2]
我想這樣做是產生一個分隔字符串列表(比如「 - 」)(或不能)各元素之間。數組中元素的順序應該保留。
所以輸出將是:
'XY2'
'X-Y-2'
'X-Y2'
'XY-2'
是有一種優雅的方式來這蟒蛇?
>>> import itertools
>>> for c in itertools.product(' -', repeat=2): print ('X%sY%s2' % c).replace(' ', '')
XY2
XY-2
X-Y2
X-Y-2
或者,從Python列表來的元素:
import itertools
a = ['X', 'Y', 2]
for c in itertools.product(' -', repeat=2):
print ('%s%s%s%s%s' % (a[0],c[0],a[1],c[1],a[2])).replace(' ', '')
或者,在一個稍微不同的風格:
import itertools
a = ['X', 'Y', '2']
for c in itertools.product(' -', repeat=2):
print ('%s'.join(a) % c).replace(' ', '')
捕獲輸出到一個列表:
import itertools
a = ['X', 'Y', '2']
output = []
for c in itertools.product(' -', repeat=len(a)-1):
output.append(('%s'.join(a) % c).replace(' ', ''))
print 'output=', output
像這樣?
from itertools import permutations
i = ["X","Y","2"]
for result in permutations(i, 3):
print "-".join(result)
結果:
X-Y-2
X-2-Y
Y-X-2
Y-2-X
2-X-Y
2-Y-X
嗨Monkut。謝謝。但是列表中元素的順序應該保留。我正在尋找的輸出在問題中指定。 – suzee
一點更廣義的,但適用於任何數量的分隔符,希望很容易在每一步明白:
import itertools
a = ['X', 'Y', '2']
all_separators = ['', '-', '+']
results = []
# this product puts all separators in all positions for len-1 (spaces between each element)
for this_separators in itertools.product(all_separators, repeat=len(a)-1):
this_result = []
for pair in itertools.izip_longest(a, this_separators, fillvalue=''):
for element in pair:
this_result.append(element)
# if you want it, here it is as a comprehension
# this_result = [element for pair
# in itertools.izip_longest(a, this_separators, fillvalue='')
# for element in pair]
this_result_string = ''.join(this_result) # check out join docs if it's new to you
results.append(this_result_string)
print results
>>> ['XY2', 'XY-2', 'XY+2', 'X-Y2', 'X-Y-2', 'X-Y+2', 'X+Y2', 'X+Y-2', 'X+Y+2']
這些是結果你的情況下,只有「」和「 - 」作爲分隔符:
>>> ['XY2', 'XY-2', 'X-Y2', 'X-Y-2']
如果你想要的一切,在一個理解:
results = [''.join(element for pair
in itertools.izip_longest(a, this_separators, fillvalue='')
for element in pair)
for this_separators in itertools.product(all_separators, repeat=len(a)-1)]
我不知道在itertool中是否有函數來實現這個功能。但我一直認爲這樣做很有趣,也是一種很好的練習。所以有一個遞歸生成器的解決方案:
def generate(liste):
if len(liste) == 1:
yield [liste]
else:
for i in generate(liste[1:]):
yield [[liste[0]]]+i
yield [ [liste[0]]+i[0] ] + i[1:]
if __name__ == "__main__":
for i in generate (["X","Y","2"]):
print "test : " + str(i)
if len(i) == 1:
print "".join(i[0])
else:
print reduce(
lambda left, right : left + "".join(right),
i,
"")
你的意思是沒有分隔符?另外,這些並不是真正的組合,只是將分隔符放到所有可能的位置。 – KobeJohn
是的,我很抱歉。元素的順序應該保留。我會做出改變 – suzee