从两个列表中创建字典时赋值中的类型不兼容[关闭]

问题描述 投票:0回答:1

将两个列表连接到字典中时,

mypy
抱怨分配中的类型不兼容。像这样:

from typing import Dict
d = Dict[str, int]

ln = ['a', 'b', 'c']
lc = [3, 5, 7]
d = dict(zip(ln, lc))
print(ln)
print(lc)
print(d)

输出表明它工作正常:

% python3 blurb.py
['a', 'b', 'c']
[3, 5, 7]
{'a': 3, 'b': 5, 'c': 7}

但是

mypy
显示:

% mypy blurb.py
blurb.py:6: error: Cannot assign multiple types to name "d" without an explicit "Type[...]" annotation
blurb.py:6: error: Incompatible types in assignment (expression has type "Dict[str, int]", variable has type "Type[Dict[Any, Any]]")
Found 2 errors in 1 file (checked 1 source file)

这是为什么呢?具体来说,第二个错误看起来令人困惑。

python python-typing mypy
1个回答
1
投票

尝试使用不同的变量名称代替

d
来表示
d = dict(zip(ln, lc))
d = Dict[str, int]

例如

from typing import Dict
d = Dict[str, int]

ln = ['a', 'b', 'c']
lc = [3, 5, 7]
x: d = dict(zip(ln, lc))
print(ln)
print(lc)
print(x)
© www.soinside.com 2019 - 2024. All rights reserved.