📜  如何遍历Python中的嵌套列表?

📅  最后修改于: 2022-05-13 01:54:25.212000             🧑  作者: Mango

如何遍历Python中的嵌套列表?

在本文中,我们将看到如何遍历嵌套列表。列表可用于存储多种数据类型,例如整数、字符串、对象,以及自身内部的另一个列表。列表中的这个子列表就是通常所说的嵌套列表。

遍历嵌套列表

让我们看看典型的嵌套列表是怎样的:

list=[10, 20, 30, 40, [ 80,60, 70 ] ]

有多种方法可以遍历嵌套列表:

方法一:使用索引遍历列表

正指数的使用:

Python3
# code
list = [10, 20, 30, 40, [80, 60, 70]]
  
# Printing sublist at index 4
print(list[4])
  
# Printing 1st element of the sublist
print(list[4][0])
  
# Printing 2nd element of the sublist
print(list[4][1])
  
# Printing 3rd element of the sublist
print(list[4][2])


Python3
# code
list = [10, 20, 30, 40, [80, 60, 70]]
  
# Printing sublist at index 4
print(list[-1])
  
# Printing 1st element of the sublist
print(list[-1][-3])
  
# Printing 2nd element of the sublist
print(list[-1][-2])
  
# Printing 3rd element of the sublist
print(list[-1][-1])


Python3
# code
# LIST
list = [["Rohan", 60], ["Aviral", 21], 
        ["Harsh", 30], ["Rahul", 40],
        ["Raj", 20]]
  
# looping through nested list using indexes
for names in list:
    print(names[0], "is", names[1],
          "years old.")


Python3
# code
# LIST
list = [["Rohan", 60], ["Aviral", 21], 
        ["Harsh", 30], ["Rahul", 40],
        ["Raj", 20]]
  
# looping through nested list using multiple 
# temporary variables
for name, age in list:
    print(name, "is",
          age, "years old.")


Python3
# code
# list
list = [10, 20, 30, 40,
        [80, 60, 70]]
  
# print the entire Sublist at index 4
print(list[4][:])
  
# printing first two element
print(list[4][0 : 2])


输出:

[80, 60, 70]
80
60
70

负指数的使用

蟒蛇3

# code
list = [10, 20, 30, 40, [80, 60, 70]]
  
# Printing sublist at index 4
print(list[-1])
  
# Printing 1st element of the sublist
print(list[-1][-3])
  
# Printing 2nd element of the sublist
print(list[-1][-2])
  
# Printing 3rd element of the sublist
print(list[-1][-1])

输出:

[80, 60, 70]
80
60
70

方法二:使用循环遍历列表


蟒蛇3

# code
# LIST
list = [["Rohan", 60], ["Aviral", 21], 
        ["Harsh", 30], ["Rahul", 40],
        ["Raj", 20]]
  
# looping through nested list using indexes
for names in list:
    print(names[0], "is", names[1],
          "years old.")

输出:

Rohan is 60 years old.
Aviral is 21 years old.
Harsh is 30 years old.
Rahul is 40 years old.
Raj is 20 years old.

在循环内使用临时变量。

蟒蛇3

# code
# LIST
list = [["Rohan", 60], ["Aviral", 21], 
        ["Harsh", 30], ["Rahul", 40],
        ["Raj", 20]]
  
# looping through nested list using multiple 
# temporary variables
for name, age in list:
    print(name, "is",
          age, "years old.")

输出:

Rohan is 60 years old.
Aviral is 21 years old.
Harsh is 30 years old.
Rahul is 40 years old.
Raj is 20 years old.

方法三:使用切片

蟒蛇3

# code
# list
list = [10, 20, 30, 40,
        [80, 60, 70]]
  
# print the entire Sublist at index 4
print(list[4][:])
  
# printing first two element
print(list[4][0 : 2])

输出:

[80, 60, 70]
[80, 60]