Python3 學習之06 (迭代器 使用)

  1. iter初始化
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


print("----------------------------------------------")
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
print ("next(it):"+ str(next(it)))   # 输出迭代器的下一个元素
print ("next(it):"+ str(next(it)))   # 输出迭代器的下一个元素

list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
for x in it:
    print (x, end=" ")

print("")
'''
import sys         # 引入 sys 模块
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
while True:
    try:
        print (next(it), end=" ")
    except StopIteration:
        sys.exit()
'''

print("#由于字符串也是可迭代对象,因此,也可以作用于for循环")
for ch in 'ABC':
    print(ch, end=" ")

print("#如果要对list实现类似Java那样的下标循环")
list=['A', 'B', 'C']
for i, value in enumerate(list):
    print(i, value)

#运行结果
----------------------------------------------
next(it):1
next(it):2
1 2 3 4 
#由于字符串也是可迭代对象,因此,也可以作用于for循环
A B C #如果要对list实现类似Java那样的下标循环
0 A
1 B
2 C

转载于:https://www.jianshu.com/p/e59c9bff5a1e

猜你喜欢

转载自blog.csdn.net/weixin_34019144/article/details/91150413
今日推荐