Python itertools.groupby 长度键?

标签 python

使用Python 3.6

有没有办法返回groupby生成器的长度作为其键?

所以这个:

from itertools import groupby

x = [1,1,1,1,1,
     2,2,2,2,
     3,3,3,
     4,4,
     5]

for key, group in groupby(x): # Some lambda function here?
    print(key,'|', group)

将输出:

5 | <itertools._grouper object at 0x0000016D0FFD45C0>
4 | <itertools._grouper object at 0x0000016D0FFD4668>
3 | <itertools._grouper object at 0x0000016D0FFD4400>
2 | <itertools._grouper object at 0x0000016D0FFD45C0>
1 | <itertools._grouper object at 0x0000016D0FFD4668>

干杯。

最佳答案

不,这是不可能的。但您始终可以将组转换为列表并打印其长度:

for key, group in groupby(x): 
    sub_list = list(group)
    print(len(sub_list),'|', sub_list)

输出:

5 | [1, 1, 1, 1, 1]
4 | [2, 2, 2, 2]
3 | [3, 3, 3]
2 | [4, 4]
1 | [5]

关于Python itertools.groupby 长度键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44897199/

相关文章:

python - 编译为不同的 python 版本

python - x,y 点数组的密度图

python - 在 Visual Studio Code 中禁用 Python 的 Jedi linting

python - 如何为 python tornado 应用程序编写单元测试?

python - Pandas dataframe - 从字典中添加列

python - 带有日期和 sqlite 的 QSortFilterProxyModel

python 查询-函数参数类型不正确?

python - 创建 Pytorch "Stack of Views"以节省 GPU 内存

python - self 属性不起作用python

python - Django_tables2 带有编辑和删除按钮。怎样做才正确呢?