【问题标题】:Grouping of items in a list of lists based on other list of lists根据其他列表列表对列表列表中的项目进行分组
【发布时间】:2018-11-13 14:53:46
【问题描述】:

我有以下列表:

mylist = [['NNP', 'NN', 'VBZ', 'VBN', 'NNP', 'NNP'],
           ['VB', 'VBN'],
           ['NNP'],
           ['VB', 'NN'],
           ['NN', 'NN']]

我还有一个列表:

cond = [['NNP', 'NN'], ['VBZ', 'VBN', 'VB']]

我想根据 cond list 中的列表对 mylist 中的列表项列表进行分组,得到如下输出。

out = [['NNP', 'NN'], ['VBZ', 'VBN'], ['NNP', 'NNP'], ['VB', 'VBN'], ['NNP'], ['VB'], ['NN'], ['NN', 'NN']]

项目应该以这样的方式分组,即 mylist 中的列表项列表应该是 cond 中的一个列表的一部分,即 ['NN', 'VBZ'] 或 ['VBN', 'NNP']预计不会输出。

这不是我必须在遇到某些项目时拆分列表的情况。

我经历了许多代码,其中列表根据条件进行拆分,但我的问题在这里有所不同。因此,这不是一个重复的问题。

我不知道开始编码的初始方法。

【问题讨论】:

  • 我不明白你的例子。条件/分组在做什么?它是两个集合之间的carthesian 产品还是过滤器?不清楚
  • 这个分组一点都不清楚。
  • 这意味着 mylist 中的每个列表都应该被拆分成新的列表,这样每个新的拆分列表应该包含来自 cond 中任何一个列表的项目,而不是来自 cond 中的两个列表。

标签: python arrays python-3.x list nested-lists


【解决方案1】:

这是我能想到的最好的:

import itertools

mylist = [['NNP', 'NN', 'VBZ', 'VBN', 'NNP', 'NNP'],
           ['VB', 'VBN'],
           ['NNP'],
           ['VB', 'NN'],
           ['NN', 'NN']]

cond = [['NNP', 'NN'], ['VBZ', 'VBN', 'VB']]

out = list()
for sublist in mylist:
    while sublist != []:
        match = list(filter(lambda x: x != [], [list(itertools.takewhile(lambda x: x in condition, sublist)) for condition in cond]))[0]
        out.append(match)
        sublist = sublist[len(match):]

print(out)

首先,我们遍历所有子列表。然后我们使用itertools 方法takewhile 构造一个匹配cond 中任何条件的元素列表。有时,给定的condition 不会有一组匹配的元素,所以我们过滤掉[] 结果。然后我们从列表的前面删除该数量的元素。我们将构建的列表添加到最终列表中。然后我们再次进入takewhile 进程,直到sublist 被耗尽。我们对mylist 中的每个子列表重复整个过程。

itertools 是 python 中一个非常强大的库,如果您经常在 python 中使用列表或其他可迭代对象,则应该熟悉它。

【讨论】:

    猜你喜欢
    • 2023-02-07
    • 2022-08-16
    • 2019-02-16
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2015-12-18
    • 2020-04-22
    • 2021-09-01
    相关资源
    最近更新 更多