【问题标题】:ValueError: too many values to unpack (expected 3) List PythonValueError:要解包的值太多(预期为 3)列出 Python
【发布时间】:2020-02-21 14:24:49
【问题描述】:

我有这个代码

car = list()
model = list()
year = list()
for cars in self.browser.find_elements_by_xpath('//td[@data-field="action_id"]'):
    car.append(cars.text)

for models in self.browser.find_elements_by_xpath('//td[@data-field="task_id"]'):
    model.append(models.text)

for years in self.browser.find_elements_by_xpath('//td[@data-field="processo"]'):
    year.append(years.text)

for x, y, z in car, model, year:
    print(x, y, z)

我从每列中删除文本以将其放入一个列表中,然后以有组织的方式阅读这 3 个列表

示例页面

Car           Model    Year
____          _____    ____
BMW           350i     2000
Chevrolet     Cruze    2018
Ford          Mustang  2017

我想要的回报

car model year
car model year
car model year

但是这个错误返回给我

ValueError:解包的值太多(预计 3 个)

这只是一个类似于我正在开发的网站的示例

【问题讨论】:

    标签: python-3.x arraylist


    【解决方案1】:

    使用 itertools 迭代多个变量

    import itertools
    #itertools.izip runs till one of the lists is exhausted
    for (x, y, z) in itertools.izip(car, model, year):
       print(x, y, z)
    #or 
    for (x, y, z) in itertools.izip_longest(car, model, year):
       print(x ,y ,z)
    #itertools.izip_longest tuns till the longest list is exhausted
    #or 
    for x, y, z in zip(car, model, year):
      print(x, y, z)
    

    您可以使用 zip 或 izip,但 izip 更好,因为 zip 一次计算所有列表,izip 仅在请求时计算元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-31
      • 2020-02-24
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      相关资源
      最近更新 更多