我有以下要求。
我有一个列表,其中包含3个元素[X,Y,2]
我想要做的是在每个元素之间(或不是)之间生成带分隔符的字符串(比如说" - ")。应保留数组中元素的顺序。
所以输出结果为:
'XY2'
'X-Y-2'
'X-Y2'
'XY-2'
在python中有一种优雅的方法吗?
答案 0 :(得分:4)
>>> 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
答案 1 :(得分:2)
稍微宽泛一点,但适用于任何数量的分隔符,希望每一步都很容易理解:
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)]
答案 2 :(得分: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,
"")
答案 3 :(得分:0)
这样的东西?
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