我是 Python (3.6) 的新手,很难理解 itertools groupby。 我有以下包含整数的列表:
list1 = [1, 2, 0, 2, 3, 0, 4, 5, 0]
但列表也可以更长,并且“0”不必出现在每对数字之后。它也可以在 3、4 或更多数字之后。我的目标是将此列表拆分为子列表,其中“0”用作分隔符并且不出现在任何这些子列表中。
list2 = [[1, 2], [2, 3], [4, 5]]
这里已经解决了类似的问题: Python spliting a list based on a delimiter word 答案 2 似乎对我有很大帮助,但不幸的是它只给了我一个 TypeError。
import itertools as it
list1 = [1, 2, 0, 2, 3, 0, 4, 5, 0]
list2 = [list(group) for key, group in it.groupby(list1, lambda x: x == 0) if not key]
print(list2)
File "H:/Python/work/ps0001/example.py", line 13, in list2 = [list(group) for key, group in it.groupby(list, lambda x: x == '0') if not key]
TypeError: 'list' object is not callable
我将不胜感激任何帮助,并很高兴最终理解 groupby。
请您参考如下方法:
您正在检查“0”(str),但您的列表中只有 0(int)。此外,您使用 list 作为第一个列表的变量名,这是 Python 中的关键字。
from itertools import groupby
list1 = [1, 2, 0, 2, 7, 3, 0, 4, 5, 0]
list2 = [list(group) for key, group in groupby(list1, lambda x: x == 0) if not key]
print(list2)
这应该给你:
[[1, 2], [2, 7, 3], [4, 5]]
