【问题标题】:ValueError: not enough values to unpack (expected 3, got 2) in a for loopValueError:没有足够的值在 for 循环中解压(预期 3,得到 2)
【发布时间】:2022-12-01 10:44:16
【问题描述】:

我正在尝试创建一个字段结构,但在 .items() 中使用包含 3 个条目的 for 循环时遇到问题。

 for pais, tipos, nombres in dirs.items():
        path_pais = os.path.join(new_path, str(pais))
        if not os.path.exists(path_pais):
            os.makedirs(os.path.join(path_pais), exist_ok=True)
        for tipo in tipos:
            path_tipos = os.path.join(path_pais, str(tipo))
            if not os.path.exists(path_tipos):
                os.makedirs(os.path.join(path_tipos), exist_ok=True)
            for nombre in nombres:
                path_nombre = os.path.join(path_tipos, str(nombre))
                if not os.path.exists(path_nombre):
                    os.makedirs(os.path.join(path_nombre), exist_ok=True)

我有这段代码,当运行它时我得到 ValueError:没有足够的值来解压(预期 3,得到 2)。 我知道 .items() 只能有 2 个条目。我在 dirs.items() 中尝试了 pais,( tipos, nombres): 但是我得到 ValueError:没有足够的值来解压(预期 2,得到 1)。 我能做些什么 ?

【问题讨论】:

  • 您应该使用 pathlib 而不是 os.path。更优雅!

标签: python for-loop valueerror items


【解决方案1】:

分配两个变量,然后在循环体中您可以将第二个变量拆分为另外两个变量。

for pais, value in dirs.items():
    tipos, nombres = value

【讨论】:

  • 或者做for pais, (tipos, nombres) in dirs.items()
猜你喜欢
  • 2021-08-21
  • 2017-09-14
  • 2017-07-04
  • 2020-07-17
  • 2019-01-05
  • 2019-09-24
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
相关资源
最近更新 更多