python 2奇怪的列表理解行为 [英] python 2 strange list comprehension behaviour

查看:71
本文介绍了python 2奇怪的列表理解行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾了列表理解功能,发现有些奇怪. 代码:

I was looking around list comprehension and saw smth strange. Code:

a = ['a', 'a', 'a', 'b', 'd', 'd', 'c', 'c', 'c']
print [(len(list(g)), k) if len(list(g)) > 1 else k for k, g in groupby(a)]

结果:

[(0, 'a'), 'b', (0, 'd'), (0, 'c')]

但是我想看看:

[(3, 'a'), 'b', (2, 'd'), (3, 'c')]

这种行为的原因是什么?

What's the cause of such behaviour?

推荐答案

itertools._grouper对象上调用list()时,将耗尽该对象.由于您执行了两次,因此第二个实例的长度为0.

When you call list() on an itertools._grouper object, you exhaust the object. Since you're doing this twice, the second instance results in a length of 0.

第一:

if len(list(g))

现在已经筋疲力尽了.然后:

now it's exhausted. Then:

(len(list(g)), k))

长度为0.

您可以在list理解中嵌套一个生成器/综合信息,以耗尽对象并保存相关数据,然后再对其进行处理:

You can nest a generator/comprehension in your list comprehension to exhaust the object and save the relevant data before processing it:

>>> [(y,x) if y>1 else x for x,y in ((k, len(list(g))) for k, g in groupby(a))]
[(3, 'a'), 'b', (2, 'd'), (3, 'c')]

这篇关于python 2奇怪的列表理解行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆