当前位置: 代码迷 >> python >> 如何使用for循环遍历Python中的嵌套列表
  详细解决方案

如何使用for循环遍历Python中的嵌套列表

热度:32   发布时间:2023-06-16 10:17:44.0

我目前正在尝试遍历并打印列表中的特定值。 我试图做到这一点的方式就是这样。

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.

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

请不要使用indees进行迭代,这很丑陋,并且被认为是非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)

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

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