【发布时间】:2018-04-02 16:55:24
【问题描述】:
我目前正在尝试更改大型字典中的所有值(变为负值)。我希望声明在一行中。我有以下字典示例:
dict = {(0,0): 1, (2, 4): 2}
我想要的是
newdict = {(0,0): -1, (2, 4): -2}
我首先尝试了几种变体
newdict = {x: -x for x in dict}
但是,我总是得到以下错误
TypeError: bad operand type for unary -: 'tuple'
我需要能够循环遍历元组键来更改所有值的东西。
【问题讨论】:
-
newdict = {key: -val for key, val in dict.items()} -
newdict = {x: -your_dict[x] for x in your_dict}或newdict = {k: -v for k, v in your_dict.items()}。另外,不要使用dict作为变量名,你不想隐藏内置... -
x在您的示例中是关键。你想否定这个值。 -
哦,哇!我觉得很傻。谢谢!我是 python 新手,忘记了你可以这样使用 key 和 val。
-
如果您发现一个有用的答案,请随时接受该答案