本文介绍了对某些(不是全部)字典值执行运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为spectradict的字典,它由5个不同的键组成(每个键有多个值),我想将4个键中的每个值乘以某个常数A.将所有值(在所有键下)乘以常数:

I have a dictionary called spectradict which is composed of 5 different keys (multiple values per key), and I'd like to multiply each value under 4 of the keys by some constant A. I've figured out how to multiply all the values (under all the keys) by the constant:

spectradict.update((x, y*A) for x, y in spectradict.items())

但是我只希望spectradict['0.001']spectradict['0.004']spectradict['0.01']spectradict['0.02']下的值乘以A.我希望spectradict['E']值保持不变.我该怎么做?

But I only want the values under spectradict['0.001'], spectradict['0.004'], spectradict['0.01'], spectradict['0.02'] to be multiplied by A. I want the spectradict['E'] values to remain unchanged. How can I accomplish this?

推荐答案

您可以通过在生成器函数的末尾附加if <test>来对生成器函数执行条件检查.

You can perform conditional checks on your generator function by appending if <test> to the end of it.

spectradict.update((k, v*A) for k, v in spectradict.items() if k != 'E')
# or, inclusive test using a set
spectradict.update((k, v*A) for k, v in spectradict.items() if k in {'0.001', '0.004', '0.01', '0.02'})

这篇关于对某些(不是全部)字典值执行运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 21:34