[英]Altering 10% of Values in Dictionary Comprehension using Python
我在进行字典理解时遇到问题。 我之前做过列表推导式,认为它们很相似,但用{}
代替。
我很确定我的random
逻辑是合理的,但对于我想要的任务。
更新字典:
import random
DLM = '~' # deliminator
programmatic_dict = {
"brand~test": "Ford",
"model~test": "Mustang",
"year~test": "2019"
}
print(programmatic_dict)
programmatic_dict = {programmatic_dict[key]: val + DLM + key.rsplit(DLM, 1)[1] else val for key, val in programmatic_dict.items() if random.randint(0,9) == 9}
print(programmatic_dict)
错误:
Traceback (most recent call last):
File "/usr/lib/python3.8/py_compile.py", line 144, in compile
code = loader.source_to_code(source_bytes, dfile or file,
File "<frozen importlib._bootstrap_external>", line 846, in source_to_code
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "./prog.py", line 13
programmatic_dict = {programmatic_dict[key]: val + DLM + key.rsplit(DLM, 1)[1] else val for key, val in programmatic_dict.items() if random.randint(0,2) == 2}
^
SyntaxError: invalid syntax
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3.8/py_compile.py", line 150, in compile
raise py_exc
py_compile.PyCompileError: File "./prog.py", line 13
programmatic_dict = {programmatic_dict[key]: val + DLM + key.rsplit(DLM, 1)[1] else val for key, val in programmatic_dict.items() if random.randint(0,2) == 2}
^
SyntaxError: invalid syntax
期望输出:
programmatic_dict = {
"brand~test": "Ford",
"model~test": "Mustang~test", # subtag in key string, added randomly at 10% (unlikely)
"year~test": "2019"
}
我的字典理解代码行哪里出错了?
请让我知道是否还有什么我可以添加到帖子中以帮助进一步澄清(因为我知道我想要完成的任务很奇怪)。
2 修订:
key:
,else val
else 语句,在 90% 的时间里,我不希望我的价值发生任何变化。programmatic_dict = {key: val + DLM + key.rsplit(DLM, 1)[1] if random.randint(0, 9) == 9 else val for key, val in programmatic_dict.items()}
文章Ctrl+F:《Python 字典理解 if else》
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.