【问题标题】:How to use a for loop to loop through a nested list in Python如何使用 for 循环遍历 Python 中的嵌套列表
【发布时间】:2017-02-16 15:18:17
【问题描述】:

我目前正在尝试循环并打印列表中的特定值。 我尝试这样做的方式是这样的。

for i in range(len(PrintedList)):
     index = i
     elem=PrintedList[i]
     print(elem)
     print ("Product = ", PrintedList [index,1], "price £",PrintedList [index,2])

但是这会返回错误:

TypeError: list indices must be integers or slices, not tuple.

我真的不确定如何解决这个问题。

【问题讨论】:

  • 贴出print(PrintedList)的输出(或小样本),让我们看看实际结构。我们无法通过查看不起作用的代码来猜测 =)
  • 你说的是PrintledList[index][1]PrintedList[index][2]吗?

标签: python list python-3.x loops for-loop


【解决方案1】:

请不要使用 indeces 进行迭代,这很丑陋并且被认为是非 Python 的。而是直接循环列表本身并使用元组赋值,即:

for product, price, *rest in PrintedList:
     print ("Product = ", product, "price £", price)

for elem in PrintedList:
     product, price, *rest = elem
     print ("Product = ", product, "price £", price)

*rest 仅在某些子列表包含超过 2 个项目(价格和产品)时才需要

如果您需要索引,请使用枚举:

for index, (product, price, *rest) in enumerate(PrintedList):
     print (index, "Product = ", product, "price £", price)

【讨论】:

  • 绝对是更pythonic的方式,我只是试图解决代码中的特定错误。 + 1 表示 *rest,我不知道。
【解决方案2】:

当您引用嵌套列表时,您在单独的括号中引用每个索引。试试这个:

for i in range(len(PrintedList)):
    index = i
    elem=PrintedList[i]
    print(elem)
    print ("Product = ", PrintedList [index][1], "price £",PrintedList [index][2])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 2020-04-26
    • 1970-01-01
    • 2019-01-15
    • 2022-01-13
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多