【问题标题】:find word combinations based on order from a list根据列表中的顺序查找单词组合
【发布时间】:2017-11-18 17:45:22
【问题描述】:

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

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

我想要的是从左边开始的组合:

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

有没有pythonic的方式来做到这一点?

【问题讨论】:

  • 尝试什么了吗?
  • 所以w1w3 不是你想要的输出?
  • 我尝试过的由两个循环组成。当列表很大时,我正在寻找更好更快的方法
  • @schwobaseggl 没错。那是我不想要的东西

标签: python list combinations permutation


【解决方案1】:

您可以使用嵌套推导

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

【讨论】:

  • 可以使用组合将其转换为列表列表吗? :[['w1', 'w1w2', 'w1w2w3', 'w1w2w3w4'],[ 'w2', 'w2w3', 'w2w3w4'], ['w3', 'w3w4'], ['w4']]
  • @AbhishekThakur 你可以做[[''.join(l[x:y]) for y in range(x + 1, len(l) + 1)] for x in range(len(l))]
【解决方案2】:

这是另一种方式...

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

【讨论】:

  • 恐怕错过了w2。
【解决方案3】:

也可以使用两个(嵌套的)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

【讨论】:

    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多