【问题标题】:Python looping through an array that can be of len 1Python 循环遍历长度为 1 的数组
【发布时间】:2020-03-20 04:24:56
【问题描述】:

我有一个字典,有时我通过的键中有数组,我通过它迭代

item for item in dict[another_key]:
   ....

但是有时候没有数组只有一个字符串,然后python抛出“TypeError: string indices must be integers”

有没有一种方法可以明确声明我只想使用数组,即使其中只有一个项目?

【问题讨论】:

  • 这不是有效的语法。它是 for 循环和列表推导的混合体,但两者都不是。
  • 你可以先检查元素的长度是否大于1。如果您想获得进一步的帮助,请提供一个最低限度的工作示例。
  • @Ibragile 检查长度是没有用的,因为字符串的长度也可以大于 1。OP 应该检查 if isinstance(dct[another_key], list)

标签: python python-3.x for-loop types


【解决方案1】:

您可以通过if type(x) is dict 检查任何变量是否为字典。

if __name__ == "__main__":
    some_dict = {"1": {"4" : 6}, "2": "test"}

    for key in some_dict: 
        if type(some_dict[key]) is dict: 
            print(f"value of key '{key}' is a dict: {some_dict[key]}")
        else: 
            print(f"value of key '{key}' is not a dict: {some_dict[key]}")

输出:

value of key '1' is a dict: {'4': 6}
value of key '2' is not a dict: test

通过这种方式,您可以轻松地区分字典值和字符串等其他值。

【讨论】:

  • K 谢谢,我以为可能有一个神奇的关键字或什么的,但看起来不像
猜你喜欢
  • 2020-05-22
  • 2020-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
相关资源
最近更新 更多