Python 中的模式匹配、元组和乘法 [英] pattern matching, tuples and multiplication in Python

查看:57
本文介绍了Python 中的模式匹配、元组和乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

减少这一系列元组的最佳方法是什么

What is be best way to reduce this series of tuples

('x', 0.29, 'a')
('x', 0.04, 'a')
('x', 0.03, 'b')
('x', 0.02, 'b')
('x', 0.01, 'b')
('x', 0.20, 'c')
('x', 0.20, 'c')
('x', 0.10, 'c')

进入:

('x', 0.29 * 0.04 , 'a')
('x', 0.03 * 0.02 * 0.01, 'b')
('x', 0.20 * 0.20 * 0.10, 'c')

X 是一个常量,它是预先知道的,可以安全地忽略

X is a constant, it is known in advance and can be safely ignored

并且可以将数据视为在上面显示的第三个元素上预先排序.

And the data can be treated as pre-sorted on the third element as it appears above.

我目前正在尝试使用 operator.mul、大量模式匹配和奇怪的 lambda 函数来做到这一点……但我相信一定有更简单的方法!

I am trying to do it at the moment using operator.mul, and a lot of pattern matching, and the odd lambda function... but I'm sure there must be an easier way!

我可以说谢谢你的所有答案吗?他们每个人都很棒,而且超出了我的期望.我所能做的就是给他们一个赞并说声谢谢!

Can I just say thank you for ALL of the answers. Each one of them was fantastic, and more than I could have hoped for. All I can do is give them all an upvote and say thanks!

推荐答案

这是一种更有状态的方法.(我更喜欢@Sven.)

Here's a more stateful approach. (I like @Sven's better.)

def combine(a)
    grouped = defaultdict(lambda: 1)

    for _, value, key in a:
        grouped[key] *= value

    for key, value in grouped.items():
        yield ('x', value, key)

如果数据已经排序,这会降低效率,因为它在内存中保留的比它需要的多.再说一次,这可能无关紧要,因为它也不是愚蠢的低效.

This is less efficient if the data are already sorted, since it keeps more in memory than it needs to. Then again, that probably won't matter, because it's not stupidly inefficient either.

这篇关于Python 中的模式匹配、元组和乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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