-locals()奇怪的行为python?

问题描述 投票:0回答:1
为什么这不起作用?

Python 3.11.6 (main, Oct 8 2023, 05:06:43) [GCC 13.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. condition ={'RAPPORT': 1, 'COMPA': 0.815, 'varie': 'N_GRAIN'} N_GRAIN, RAPPORT, COMPA, ACC, FREQ = 0.,0.,0.,0.,0. print(locals()['RAPPORT']) 0.0 match = all(condition[key] == locals()[key] for key in condition if key != 'varie') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <genexpr> KeyError: 'RAPPORT'

我不明白为什么它给了我一个钥匙扣,因为“融洽关系”处于状态,在当地人()!?

I在Python2上重现了它,但具有不同的键错误。这是代码:

Python 2.7.18 (default, Oct 15 2023, 16:43:11) [GCC 11.4.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. condition ={'RAPPORT': 1, 'COMPA': 0.815, 'varie': 'N_GRAIN'} N_GRAIN, RAPPORT, COMPA, ACC, FREQ = 0.,0.,0.,0.,0. print(locals()['RAPPORT']) 0.0 match = all(condition[key] == locals()[key] for key in condition if key != 'varie') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <genexpr> KeyError: 'COMPA'

	
您的发电机创建了一个新的范围,以使当地人()现在与外部范围不同。 您可以通过以下方式解决此问题:
python local-variables keyerror short wsl2
1个回答
0
投票
condition = {"RAPPORT": 1, "COMPA": 0.815, "varie": "N_GRAIN"} N_GRAIN, RAPPORT, COMPA, ACC, FREQ = 0.0, 0.0, 0.0, 0.0, 0.0 locals_ = locals() all(condition[key] == locals_[key] for key in condition.keys() if key != 'varie')

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.