Python迭代列表

时间:2020-02-23 14:42:51  来源:igfitidea点击:

Python列表基本上是用于数组的目的,并其中存储数据/元素。

可以通过多种方式遍历列表。

在Python中迭代列表的方法

1.使用for循环迭代列表

Python for循环可用于遍历List。

例:

input_list = [10, "Safa", 15, "Aman", 1] 

for x in input_list: 
	print(x) 

输出:

10
Safa
15
Aman
1

2.通过while循环迭代列表

Python while循环可用于遍历列表。

例:

input_list = [10, "Safa", 15, "Aman", 1] 

length_list = len(input_list) 
x = 0

while x < length_list: 
  print(input_list[x]) 
  x += 1

输出:

10
Safa
15
Aman
1

3.列表理解以迭代Python列表

Python List Comprehension也可以用于有效地遍历列表。

列表理解是创建和遍历列表的一种简便方法。

例:

input_list = [10, "Safa", 15, "Aman", 1] 
[print(x) for x in input_list] 

输出:

10
Safa
15
Aman
1

4.使用for Loop和range()函数的Python迭代列表

使用range()方法,用户可以创建指定范围内的一系列元素。

Python for Loop和range()函数可用于遍历列表。

例:

input_list = [10, "Safa", 15, "Aman", 1] 
length_list = len(input_list) 
 
for x in range(length_list): 
  print(input_list[x]) 

输出:

10
Safa
15
Aman
1

5.使用NumPy的Python迭代列表

Python NumPy基本上是一个库,可用于对大量数据执行操作和操作,以提供数组功能。

NumPy可用于遍历具有大量数据的列表。

例:

import numpy as n

x = n.arange(12) 

 
x = x.reshape(3, 4) 

for i in n.nditer(x): 
	print(i) 

在上面的示例中,numpy.arange(value)函数根据提供的参数值帮助返回数组中均匀间隔的项目。

通过reshape()函数,用户可以通过向其提供参数值来为现有数组提供新形状,而无需更改插入其中的数据。

numpy.nditer基本上是一个迭代器对象,用于遍历列表/数组。

输出:

0
1
2
3
4
5
6
7
8
9
10
11

6. Python enumerate()函数迭代列表

Python enumerate()函数基本上是一种遍历/迭代列表的简单技术。

例:

input_list = [10, "Safa", 15, "Aman", 1] 
for x, result in enumerate(input_list): 
  print (x, ":",result) 

输出:

0 : 10
1 : Safa
2 : 15
3 : Aman
4 : 1

同时遍历多个列表

Python zip()函数用于同时遍历多个列表。

它基本上会考虑所有列表中较小的一个,并相应地提供输出。

如果任何一个列表用尽或者遍历,zip()函数将停止。

例:

import itertools  

age = [21, 28, 31] 
gender = ['Male', 'Female', 'Others'] 
city = ['Pune', 'Mumbai'] 

for (x, y, z) in zip(age, gender, city): 
  print (x, y, z) 
  

输出:

21 Male Pune
28 Female Mumbai