是否可以将此代码片段转换为列表理解?如何?
a = 0 b = {'a': [(1, 'a'), (2, 'b'), (3, 'c')], 'b': [(4, 'd'), (5, 'e')]} for c, d in b.iteritems(): for e, f in d: a += e // now a = 15
尝试了几种方法。我想知道一种方法(如果可能的话)通过列表理解来简化这个总和:
a = sum(...)
提前谢谢您, pf.me
a = 0 b = {'a': [(1, 'a'), (2, 'b'), (3, 'c')], 'b': [(4, 'd'), (5, 'e')]} for c, d in b.iteritems(): for e, f in d: a += e // now a = 15
Tried several ways. I want to know a way (if possible) to simplify this sum with a list comprehension:
a = sum(...)
Thank you in advance,
pf.me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
a = sum(e for d in b.itervalues() for e, _ in d)
适用于 Python 2.7。a = sum([e for d in b.itervalues() for e, _ in d])
适用于 Python 2.3。我还没有尝试过,但是
a = sum(e for d in b.values() for e, _ in d)
应该是 Python 3.0 的等效项。a = sum(e for d in b.itervalues() for e, _ in d)
works in Python 2.7.a = sum([e for d in b.itervalues() for e, _ in d])
works in Python 2.3.I haven't tried it, but
a = sum(e for d in b.values() for e, _ in d)
should be the Python 3.0 equivalent.sum(j for _,i in b.iteritems() for j,_ in i)
就可以了。sum(j for _,i in b.iteritems() for j,_ in i)
will do it.