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]])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。