首页 > 编程语言 > 详细

Python中的迭代(Iteration)

时间:2021-05-02 16:35:10      阅读:22      评论:0      收藏:0      [点我收藏+]

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)

原文:https://www.cnblogs.com/musicalife/p/14725627.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!