【问题标题】:ValueError: too many values to unpack (expected 2) while iterating over a listValueError:迭代列表时要解包的值太多(预期为 2)
【发布时间】:2022-01-15 08:44:08
【问题描述】:

我有一个清单:

imageList = [(cloud/image_stored_docker:1.1.0, tarfile-1.1.0.tar),
             (cloud/image_stored_docker:1.2.0, tarfile-1.2.0.tar)]

我需要分成两个列表,一个带有键的列表(其中图像是键),另一个带有值(tarfile)。

我正在尝试创建一个字符串,然后将其转换为列表

for key, value  in imageList.items():
    images = images + key + ","

images = list(images)

但我收到此消息:

for key, value  in imageList.items():
AttributeError: 'list' object has no attribute 'items'

我尝试了其他方法;删除 items() 函数,这是消息:

for key, value  in imageList:
ValueError: too many values to unpack (expected 2)

去掉最后的绒毛。\

【问题讨论】:

  • 我认为删除“.items()”。这不是字典,它是对的列表。
  • 遍历 imageList 中的每个元组,并将元组分离为键和值。
  • imageList 中的项目是两个字符串的元组吗?您的问题不清楚,因为显示的内容在语法上无效。

标签: python list loops dictionary unix


【解决方案1】:

如果你只想打印一个键列表,你可以使用列表推导并遍历元组

imageList = [("cloud/image_stored_docker:1.1.0", "tarfile-1.1.0.tar"), ("cloud/image_stored_docker:1.2.0", "tarfile-1.2.0.tar") ]
keys = [pair[0] for pair in  imageList]
print(",".join(keys))

输出

cloud/image_stored_docker:1.1.0,cloud/image_stored_docker:1.2.0

【讨论】:

  • 非常感谢!!!
猜你喜欢
  • 1970-01-01
  • 2014-07-31
  • 2017-08-29
  • 1970-01-01
  • 2021-06-24
  • 2016-05-24
  • 1970-01-01
  • 2017-12-14
相关资源
最近更新 更多