ITPub博客

首页 > IT职业 > IT职场 > python有几种循环遍历的方法?

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

IT职场 作者:tonydeck 时间:2021-09-11 09:57:23 0 删除 编辑

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])

以上就是python2种循环遍历的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4615/viewspace-2830301/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 有哪些反爬虫
请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    84
  • 访问量
    966