Python中的迭代(Iteration)

2021/5/2 20:30:50

本文主要是介绍Python中的迭代(Iteration),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Python中的迭代

迭代器种类

1. enumerate()
2. items()
3. np.nditer()
4. iterrows()

不同迭代器之间的区别:

迭代器的名称 迭代器的特点
enumerate() 迭代的同时生成索引信息
items() 用于字典同时迭代生成关键字和对应内容
np.nditer() 用于迭代一个numpy多维数组(默认先行后列)
iterows() 用于迭代一个pandas数组

使用迭代器的实例

enumerate()

# Input:
l = ['a', 'b', 'c']
for index, item in enumerate(l):
    print(index, ':', item)

# Output:
0 : a
1 : b
2 : c

items()

# Input:
dict = {'name:': 'xiaoming', 'grade': '59'}
for key, item in dict.items():
    print(key, ':', item)

# Output:
name: : xiaoming
grade : 59

np.nditer()

# Input:
a = np.array([[1, 2], [4, 5]])
it = np.nditer(a1, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
    ix = it.multi_index
    a[ix] += 100
    it.iternext()

# Output:
a
array([[101, 102],
       [104, 105]])



这篇关于Python中的迭代(Iteration)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程