python有几种循环遍历的方法?

475次阅读
没有评论

python有几种循环遍历的方法?

1、for-in可以用来遍历数组与字典。

words = ['cat', 'window', 'defenestrate']
 
for w in words:
    print(w, len(w))
 
# 使用数组访问操作符,能够迅速地生成数组的副本
for w in words[:]:
    if len(w) > 6:
        words.insert(0, w)
 
# words -> ['defenestrate', 'cat', 'window', 'defenestrate']

2、如果希望使用数字序列进行遍历,可以使用Python内置的range函数。

a = ['Mary', 'had', 'a', 'little', 'lamb']
 
for i in range(len(a)):
    print(i, a[i])
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-28发表,共计487字。
新手QQ群:570568346,欢迎进群讨论 Python51学习