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

Abh*_*kur -1 python combinations list permutation

我有一个如下的单词列表:

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

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

w1, w1w2, w1w2w3, w1w2w3w4, w2, w2w3, w2w3w4, w3, w3w4, w4
Run Code Online (Sandbox Code Playgroud)

有这样做的pythonic方式吗?

sch*_*ggl 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']
Run Code Online (Sandbox Code Playgroud)

或者你可以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)]
Run Code Online (Sandbox Code Playgroud)