gpt4 book ai didi

python - Python 中的模式匹配、元组和乘法

转载 作者:行者123 更新时间:2023-11-28 19:40:25 25 4
gpt4 key购买 nike

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

('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 是一个常量,它是预先知道的,可以安全地忽略

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

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

我能说谢谢你所有的答案吗?他们每个人都很棒,超出了我的期望。我所能做的就是给他们全部投票并表示感谢!

最佳答案

这是一种函数式编程方法:

from itertools import imap, groupby
from operator import itemgetter, mul

def combine(a):
for (first, last), it in groupby(a, itemgetter(0, 2)):
yield first, reduce(mul, imap(itemgetter(1), it), 1.0), last

关于python - Python 中的模式匹配、元组和乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11004838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com