【问题标题】:Python get combination of continous words [duplicate]Python得到连续词的组合[重复]
【发布时间】:2022-01-20 04:04:15
【问题描述】:

我有一个这样的列表:

tokens = ["hi", "how", "are", "you"]

我正在尝试获取最多 n=3 的单词组合 我的预期输出是:

output = [ ["hi"], ["hi", "how" ], ["hi", "how" , "are"], ["how"], ["how", "are"], ["how", "are", "you"], ["are"], ["are", "you"], ["you"]

我的代码:

comb = []
for i in range(3):
    comb += list(itertools.combinations(tokens,i+1))

但我的代码提供了所有内容的组合,而不仅仅是下一个单词。这里有什么问题?

【问题讨论】:

  • 这种情况下,需要自己制作算法。 itertools 可能无法胜任。
  • 您可以使用2个循环一个一个来选择数组长度的起点和另一个,然后复制数组并将其存储在一个新数组中。

标签: python list combinations itertools


【解决方案1】:

请检查此代码 sn-p 是否解决了您的目的,您可以使用此代码:

import itertools
tokens = ["hi", "how", "are", "you"]

output = [tokens[start:end] for start, end in itertools.combinations(range(len(tokens)+1), 2)]
output

输出:

[['hi'], ['hi', 'how'], ['hi', 'how', 'are'], ['hi', 'how', 'are', 'you'], ['how'], ['how', 'are'], ['how', 'are', 'you'], ['are'], ['are', 'you'], ['you']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2011-09-02
    • 2021-07-16
    • 2011-07-05
    • 2018-07-26
    相关资源
    最近更新 更多