📜  Python - 在不使用增量变量的情况下遍历列表

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

Python - 在不使用增量变量的情况下遍历列表

Python 列表很像灵活大小的数组,在 C++ 中的向量、 Java中的数组列表等其他语言中声明。列表是异构的,使其成为Python中最有效的特性。列表是可变的,因此即使在它们形成之后也可以修改。

最常见的方法是使用增量变量i 遍历列表:

Python3
# Initializing the list
List = ["Geeks", 4, 'Geeks!']
 
# Using index variable to access
# each element of the list
for i in range(len(List)):
    print(List[i], end=" ")


Python3
# Initializing the list
List = ["Geeks", 4, 'Geeks!']
 
# Using a common variable to access
# each element of the list
for ele in List:
    print(ele, end=" ")


Python3
# Initializing the list
List = ["Geeks", 4, 'Geeks!']
 
# Using enumerate()
for ele in enumerate(List):
    print(ele[1], end=" ")


Python3
# Importing required modules
import numpy
 
# Initializing the list
List = ["Geeks", 4, 'Geeks!']
 
# Converting to array
Array = numpy.array(List)
 
# Using enumerate
for ele in numpy.nditer(Array):
    print(ele, end=" ")


输出:

Geeks 4 Geeks! 

这是最常见的做法,其中索引变量i用于仅使用该列表中该元素的索引来访问该列表的每个元素。但是,有多种方法可以在不使用索引变量的情况下遍历列表。

下面是一些在不使用索引变量的情况下迭代列表的方法:

方法一:

使用每个元素的公共变量而不是索引显式迭代列表。

蟒蛇3

# Initializing the list
List = ["Geeks", 4, 'Geeks!']
 
# Using a common variable to access
# each element of the list
for ele in List:
    print(ele, end=" ")

输出:

Geeks 4 Geeks! 

方法二:

enumerate()方法向列表中添加一个计数器并以枚举对象的形式返回它,该对象可用于访问列表的元素

蟒蛇3

# Initializing the list
List = ["Geeks", 4, 'Geeks!']
 
# Using enumerate()
for ele in enumerate(List):
    print(ele[1], end=" ")

输出:

Geeks 4 Geeks! 

方法三:

numpy中使用nditer()方法 在将列表转换为数组后迭代列表。  

蟒蛇3

# Importing required modules
import numpy
 
# Initializing the list
List = ["Geeks", 4, 'Geeks!']
 
# Converting to array
Array = numpy.array(List)
 
# Using enumerate
for ele in numpy.nditer(Array):
    print(ele, end=" ")

输出:

Geeks 4 Geeks!