Python 将列表的元素与所有可能的分隔符组合在一起
我有以下要求 我有一个列表,上面有3个元素Python 将列表的元素与所有可能的分隔符组合在一起,python,python-2.7,Python,Python 2.7,我有以下要求 我有一个列表,上面有3个元素[X,Y,2] 我想做的是在每个元素之间(或不是)生成带有分隔符(比如“-”)的字符串。应保留数组中元素的顺序 因此,输出将是: 'XY2' 'X-Y-2' 'X-Y2' 'XY-2' 在python中有没有一种优雅的方法可以做到这一点?类似的东西 from itertools import permutations i = ["X","Y","2"] for result in permutations(i, 3): print "-".
[X,Y,2]
我想做的是在每个元素之间(或不是)生成带有分隔符(比如“-”)的字符串。应保留数组中元素的顺序
因此,输出将是:
'XY2'
'X-Y-2'
'X-Y2'
'XY-2'
在python中有没有一种优雅的方法可以做到这一点?类似的东西
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
或者,对于来自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
更一般化一点,但适用于任何数量的分离器,希望在每一步都易于理解:
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,
"")
你是说有分离器和没有分离器?而且,这些并不是真正的组合,只是将分离器置于所有可能的位置。是的,我很抱歉。应保持元素的顺序。我会做出改变的。谢谢但是列表中元素的顺序应该保留。问题中指定了我要查找的输出。不错,但列表在哪里?:)@RaulGuiu好的,我添加了两个表单,其中一个列表是源代码。让我知道他们是否是你要找的。这太棒了。谢谢@John1024。将结果添加到另一个列表。在itertools.product('-',repeat=len(a)-1):b.append(str(“%s”).join(a)%c.replace(''')@suzee好主意。我也在答案中加入了这个表格。
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,
"")