Solving "error: Unsupported left operand type for + ("Iterable[str]") [operator]"

Solving "error: Unsupported left operand type for + ("Iterable[str]") [operator]"

我有代码接受字符串列表,并将它们转换为标记列表(即所有字符串都被组合并展平)

例如,['a b', 'c', 'd e'] => ['a', 'b', 'c', 'd', 'e']

像这样:

l = ['a b', 'c', 'd e']
set(reduce(lambda a, b: a + b.split(), l, []))

不幸的是,mypy不高兴,它给出了消息:error: Unsupported left operand type for + ("Iterable[str]") [operator]

回答所示,是因为sequences do not necessarily implement __add__.

那么,有没有办法使用代码 set(reduce(lambda a, b: a + b.split(), l, [])) 并使其与 mypy 兼容?

通过强制转换,您可以使用 lambda(否则使用 def 函数):

l = ['a b', 'c', 'd e']
reduce(lambda a, b: cast(list, a) + b.split(), l, [])