根据列表中的顺序查找单词组合

时间:2017-11-18 17:45:22

标签: python list combinations permutation

我有以下单词列表:

[w1, w2, w3, w4](N字)。

我想得到的是从左开始的组合:

w1, w1w2, w1w2w3, w1w2w3w4, w2, w2w3, w2w3w4, w3, w3w4, w4

有这样做的pythonic方法吗?

4 个答案:

答案 0 :(得分:6)

您可以使用嵌套理解

l = ['1', '2', '3', '4']
[''.join(l[x:y]) for x in range(len(l)) for y in range(x + 1, len(l) + 1)]
# ['1', '12', '123', '1234', '2', '23', '234', '3', '34', '4']

或者您可以使用itertools.combinations来缩短它

from itertools import combinations
[''.join(l[x:y]) for x, y in combinations(range(len(l) + 1), 2)]
# or to get lists:
[l[x:y] for x, y in combinations(range(len(l) + 1), 2)]

答案 1 :(得分:1)

这是另一种方式......

l1 = ['w1', 'w2', 'w3', 'w4']
str = ''
i=0

while i < len(l1):
    str=''
    for j in range(i,len(l1)):
        str+= l1[j]
        print(str)
    i+=1

输出

w1
w1w2
w1w2w3
w1w2w3w4
w2
w2w3
w2w3w4
w3
w3w4
w4

答案 2 :(得分:0)

也可以使用两个(嵌套)for循环以简单的方式完成:

words = ['w1', 'w2', 'w3', 'w4']
for i in range(len(words)):
    for j in range(i, len(words)):
        print("".join(words[i:j+1])) # take all the words between i and j and concatenate them

<强>输出

w1
w1w2
w1w2w3
w1w2w3w4
w2
w2w3
w2w3w4
w3
w3w4
w4

答案 3 :(得分:0)

itertools.accumulate()方法:

import itertools

l = ['w1', 'w2', 'w3', 'w4']
result = [s for i in range(len(l)) for s in itertools.accumulate(l[i:], lambda t,w: t + w)]

print(result)

输出:

['w1', 'w1w2', 'w1w2w3', 'w1w2w3w4', 'w2', 'w2w3', 'w2w3w4', 'w3', 'w3w4', 'w4']