我可以根据两个值将列表理解缩减为两个列表吗?
我有以下代码。
sum_review = reduce(add,[book['rw'] for book in books])
sum_rating = reduce(add,[book['rg'] for book in books])
items = len(books)
avg_review = sum_review/items
avg_rating = sum_rating/items
我想要的是这个。
sum_review,sum_rating = reduce(add,([book['rw'],[book['rg']) for book in books])
items = len(books)
avg_review = sum_review/items
avg_rating = sum_rating/items
显然这是行不通的。在没有常规循环的情况下如何解决这种冗余?
I've got the following code.
sum_review = reduce(add,[book['rw'] for book in books])
sum_rating = reduce(add,[book['rg'] for book in books])
items = len(books)
avg_review = sum_review/items
avg_rating = sum_rating/items
What I'd like is this.
sum_review,sum_rating = reduce(add,([book['rw'],[book['rg']) for book in books])
items = len(books)
avg_review = sum_review/items
avg_rating = sum_rating/items
Obviously this doesn't work. How can I solve this redundancy, without a regular loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会避免在这里使用reduce。对于如此简单的事情,请使用
sum
:在我看来,这个更简单的版本不需要重构来消除冗余。只有两个项目(
rw
和rg
),我认为最好保持原样。I'd avoid using reduce here. For something so simple use
sum
:In my opinion this simpler version doesn't need refactoring to remove redundancy. With just two items (
rw
andrg
) I think it's best to just leave it as it is.有两种典型的简化代码的方法:
自上而下:首先获取值,然后使用
zip(*iterable) 转置它们
。它也很酷,因为它只迭代集合一次:自下而上:创建一个函数来抽象操作:
There are two typical approaches to simplify code:
Top-down: get the values first and then transpose them with
zip(*iterable)
. It's also cool because it only iterates the collection once:Bottom-up: create a function to abstract the operation:
(已测试)
(tested)
你应该更喜欢清晰而不是优化。在使用 Python 的 3 年里,我只需要分析两次就可以发现性能瓶颈。您的原始代码清晰高效。将前两行压缩为一行会损害可读性并且几乎不会影响性能。
如果我必须修改你的代码,它会是这样的:(
将五行代码减少到两行,并提高了清晰度。)
You should prefer clarity over optimization. In 3 years of using Python, I have only had to profile to discover performance bottlenecks twice. Your original code is clear and efficient. Compressing the first two lines into one hurts readability and barely impacts performance.
If I had to revise your code, it would like this:
(That's five lines of code down to two with an improvement of clarity.)
当然可以通过创建一个函数:
By making a function, of course: