【问题标题】:How to unpack a list of tuples with enumerate? [duplicate]如何使用枚举解包元组列表? [复制]
【发布时间】:2017-08-18 15:33:50
【问题描述】:

我偶然发现了一个我无法解释的解包问题。

这行得通:

tuples = [('Jhon', 1), ('Jane', 2)]

for name, score in tuples:
    ...

这也有效

for id, entry in enumerate(tuples):
    name, score = entry
    ...

但这不起作用:

for id, name, score in enumerate(tuples):
    ...

抛出 ValueError: need more than 2 values to unpack 异常。

【问题讨论】:

    标签: python python-3.x tuples iterable-unpacking


    【解决方案1】:

    enumerate 本身使用列表值及其对应的索引创建元组。在这种情况下:

    list(enumerate(tuples))
    

    给予:

    [(0, ('Jhon', 1)), (1, ('Jane', 2))]
    

    要完全解压,你可以试试这个:

    for index, (name, id) in enumerate(tuples):
         pass
    

    这里,Python 将右侧的索引和元组对象与左侧的结果进行配对,然后进行赋值。

    【讨论】:

      【解决方案2】:

      解包时将name 和score 包装在一个元组中。

      for id, (name, score) in enumerate(tuples):
          print(id, name, score)
      
      # Output
      # (0, 'Jhon', 1)
      # (1, 'Jane', 2)
      

      enumerate(thing),其中 thing 是迭代器或序列,返回一个迭代器,该迭代器将返回 (0, thing[0]), (1, thing[1]), (2, thing[2]) ,等等。

      在这种情况下,thing 是一个元组。

      【讨论】:

        猜你喜欢
        • 2020-05-04
        • 1970-01-01
        • 2021-03-25
        • 1970-01-01
        • 2012-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        相关资源
        最近更新 更多