给字典元素分配名称

huangapple go评论100阅读模式
英文:

Assigning Name to Dictionary Element

问题

我有一个字典,其中键是元组,值是浮点数。我有类似下面的代码:

对于字典中的每个长元组键:
    字典[长元组键] += func(字典[长元组键])
    字典[长元组键] *= func2(字典[长元组键])

我想将其简化为类似下面的代码:

对于字典中的每个长元组键:
    val = 字典[长元组键]
    val += func(val)
    val *= func2(val)

当然,上面的代码将val定义为不可变的浮点数,并且无法修改字典条目。有办法实现这个吗?

英文:

I have a dictionary with tuples as keys and floats as values. I have code that looks like

For each longtuplekey in dictionary:
    dictionary[longtuplekey]+=func(dictionary[longtuplekey])
    dictionary[longtyplekey]*=func2(dictionary[longtuplekey])

I'd like it to shorten it to something like

For each longtuplekey in dictionary:
    val=dictionary[longtuplekey]
    val+=func(val)
    val*=func2(val)

Except of course that the above code defines val as an immutable float and fails to modify the dictionary entry. Is there a way to do this?

Edit: I've selected the answer that says "No, there's no explicit way to do this" and provides an alternative. If anyone comes up with a way to do exactly what I wanted, I will change the answer.

答案1

得分: 2

这里无需使用2次赋值,只需在imul赋值内部同时执行两个函数,并使用 dict.items 来同时遍历键和值:

for longtuplekey, val in dictionary.items():
    dictionary[longtuplekey] *= func2(val + func(val))
英文:

There's no need to use 2 assignments here, just do both funcs inside the imul assignment and use dict.items to loop over the keys and values simultaneously:

for longtuplekey, val in dictionary.items():
    dictionary[longtuplekey] *= func2(val + func(val))

答案2

得分: 1

以下是翻译好的内容:

没有绝对可靠的方法让Python识别到对val的赋值应该更新字典中的值。如果你想要更新字典,你需要重新赋值给它。好消息是,你可以通过迭代字典的items()而不仅仅是它的键来减少所需的dictionary[longtuplekey]的用法。

for longtuplekey, val in d.items():
    val += func(val)
    val *= func2(val)
    d[longtuplekey] = val
英文:

There's no bulletproof way to make Python recognize that assignments to val should update the value in the dictionary too. If you want to update the dict, you'll have to assign back to it. On the bright side, you can reduce the number of required dictionary[longtuplekey] usages by iterating over the dict's items() rather than just its keys.

for longtuplekey, val in d.items():
    val += func(val)
    val *= func2(val)
    d[longtuplekey] = val

答案3

得分: 1

你可以这样做:

for longtuplekey in dictionary:
    val = dictionary[longtuplekey]
    val += func(val)
    val *= func2(val)
    dictionary[longtuplekey] = val
英文:

You can do something like this:

for longtuplekey in dictionary:
    val = dictionary[longtuplekey]
    val += func(val)
    val *= func2(val)
    dictionary[longtuplekey] = val

huangapple
  • 本文由 发表于 2020年1月4日 00:23:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定