python - python groupby和list交互
问题描述
如果我们运行以下代码,
from itertools import groupby
s = '1223'
r = groupby(s)
x = list(r)
a = [list(g) for k, g in r]
print(a)
b =[list(g) for k, g in groupby(s)]
print(b)
然后令人惊讶的是,两条输出线是不同的:
[]
[['1'], ['2', '2'], ['3']]
但是如果我们删除行“x=list(r)”,那么这两行是相同的,正如预期的那样。我不明白为什么 list() 函数会改变 groupby 结果。
解决方案
The result of groupby
, as with many objects in the itertools
library, is an iterable that can only be iterated over once. This is to allow lazy evaluation. Therefore, when you call something like list(r)
, r
is now an empty iterable.
When you iterate over the empty iterable, of course the resulting list is empty. In your second case, you don't consume the iterable before you iterate over it. Thus, the iterable is not empty.
推荐阅读
- microsoft-teams - pulseaudio“别名”接收器,由(运行时可切换)其他接收器支持
- javascript - JavaScript - 创建一个按顺序调用事件的按钮
- mysql - 在 google cloud 上运行的 Lamp stack 并想创建一个副本数据库
- javascript - 无法使用 three.js 更改我的 3D 模型的颜色
- c# - C#/Selenium .Net 转换 ro .Core 错误
- python - 来自 fortran 的数字太大:ValueError:无法将字符串转换为浮点数:'0.22738+109'
- javascript - For Loop Google App Script Javascript 的更快替代方案
- html - 当用户在日历上选择其他日期时,PrimeNG 日历清除当前/今天日期
- android - 带有片段的 NavigationDrawer 内的 Android TabLayout
- android - 谷歌 Android kotlin 代码实验室;我可以使用 RecyclerView.ViewHolder 替换所有 PhotoGridAdapter.MarsPropertyViewHolder 吗?