将列表中的元素与所有可能的分隔符组合在一起

2024-10-01 17:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下要求。在

我有一个列表,上面说有3个元素[X,Y,2]

我想做的是在每个元素之间(或者不是)用分隔符(比如“-”)生成字符串。应该保留数组中元素的顺序。在

所以输出结果是:

'XY2'
'X-Y-2'
'X-Y2'
'XY-2'

在python中有没有一种优雅的方法来实现这一点?在


Tags: 方法字符串元素列表顺序数组xy分隔符
3条回答

更概括一点,但适用于任何数量的分离器,希望每个步骤都易于理解:

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

以下是仅使用“”和“-”作为分隔符的情况的结果:

^{pr2}$

如果你想把所有事情都放在一个理解中:

^{3}$

我不知道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,
            "")
>>> import itertools
>>> for c in itertools.product(' -', repeat=2): print ('X%sY%s2' % c).replace(' ', '')
XY2
XY-2
X-Y2
X-Y-2

或者,如果元素来自python列表:

^{pr2}$

或者,以稍微不同的风格:

^{3}$

要将输出捕获到列表:

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

相关问题 更多 >

    热门问题