【问题标题】:How to type check a nested list of integers and convert to string? [duplicate]如何键入检查嵌套的整数列表并转换为字符串? [复制]
【发布时间】:2022-01-05 19:11:15
【问题描述】:

如果我有包含列表和整数值的 kwarg,我如何键入检查 for if 循环中的项目? 我不断收到TypeError: 'int' is not iterable,否则它会跳过 if 语句。

我已经尝试过运算符 ==!=isis notlistListitertype(list)int

示例: 如果我的 kwarg 是……

kwargs = {'foo': [1, 2], 'bar': 2, 'baz': 3}
new_list = []
for kw, args in kwargs.items():
    if args == list:
        for arg in args:
            new_list.append(str(arg))
    else:
        new_list.append(str(args))
print(new_list)
>>> ['[1, 2]', '2', '3']

如果我将 if 语句切换到 if args != int: 我会得到 TypeError: 'int' is not iterable

【问题讨论】:

  • 如果你想检查某个东西是否是一个列表,你可以这样做if isinstance(args, list):

标签: python operators typing control-flow generic-collections


【解决方案1】:

要检查变量是否为列表,您可以简单地编写:

if isinstance(var, list):
    pass

但如果变量可以是任何可迭代的,请使用类型模块。

from typing import Iterable  # or from collections.abc import Iterable

if isinstance(var, Iterable):
    pass

您可以使用许多其他抽象基类,因此我建议您阅读文档以了解它们。

https://docs.python.org/3/library/typing.html

https://docs.python.org/3/library/collections.abc.html

【讨论】:

    猜你喜欢
    • 2021-05-01
    • 2016-02-08
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2019-04-24
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多