• 如果觉得本站的内容有帮助,可以考虑打赏博主哦!

  • 本站会放置Google广告用于维持域名以及网站服务器费用。

  • 在本站开通年度VIP,无限制下载本站资源和阅读本站文章

  • 感谢大家访问本站,希望本站的内容可以帮助到大家!

  • 本站由于前段时间遭受到大量临时和国外邮箱注册,所以对可注册的邮箱类型进行了限制!

  • 计算机图形学与计算几何经典必备书单整理,下载链接可参考:https://www.stubbornhuang.com/1256/

  • 工资「喂饱肚子」,副业「养活灵魂」!

  • 欢迎大家交换友链,可在https://www.stubbornhuang.com/申请友情链接进行友链交换申请!

  • 问题反馈可发送邮件到stubbornhuang@qq.com

Python – 列表list遍历方法总结

Python 发布于2022-06-22 阅读 2,129次 0次评论 0次点赞 本文共1331个字,阅读需要4分钟。

1 列表list遍历的方法

1.1 按值遍历list

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    my_list = ['hello','world','C++','python']

    for item in my_list:
        index = my_list.index(item)
        print('索引:{},值:{}'.format(index,item))

输出

索引:0,值:hello
索引:1,值:world
索引:2,值:C++
索引:3,值:python

这种for item in my_list的方法主要是对list中的值进行遍历,然后再通过值求解索引,不过如果list有两个相同的值时,通过list.index()方法求解索引可能会出现问题,比如

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    my_list = ['hello','world','hello','python']

    for item in my_list:
        index = my_list.index(item)
        print('索引:{},值:{}'.format(index,item))

输出

索引:0,值:hello
索引:1,值:world
索引:0,值:hello
索引:3,值:python

这里出问题的是list中的第3个值hello的索引,list.index()一般是返回被查询的值第一次出现的索引,所以才导致上述索引出现错误。

1.2 根据list长度,按索引遍历list

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    my_list = ['hello','world','hello','python']

    for i in range(len(my_list)):
        print('索引:{},值:{}'.format(i,my_list[i]))

输出

索引:0,值:hello
索引:1,值:world
索引:2,值:hello
索引:3,值:python

1.3 使用enumerate,返回(index,value)遍历list - 推荐方法

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    my_list = ['hello','world','hello','python']

    for idx,val in enumerate(my_list):
        print('索引:{},值:{}'.format(idx,val))

输出

索引:0,值:hello
索引:1,值:world
索引:2,值:hello
索引:3,值:python

此外enumerate还可以指定遍历起始的索引,例如

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    my_list = ['hello','world','hello','python']

    for idx,val in enumerate(my_list,4):
        print('索引:{},值:{}'.format(idx,val))

输出

索引:4,值:hello
索引:5,值:world
索引:6,值:hello
索引:7,值:python

此方法只是改变开始索引的值,并不改变遍历顺序。

欢迎扫码关注我的微信公众号,及时获取文章更新

微信公众号二维码

本文作者:StubbornHuang

版权声明:本文为站长原创文章,如果转载请注明原文链接!

原文标题:Python – 列表list遍历方法总结

原文链接:https://www.stubbornhuang.com/2176/

发布于:2022年06月22日 10:06:20

修改于:2023年06月25日 21:05:17

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

文章末尾
上一篇
Pytorch - 内置的CTC损失函数torch.nn.CTCLoss参数详解与使用示例
Pytorch
下一篇
Python - glob模块详解以及glob.glob、glob.iglob函数的使用
Python
当前分类随机文章推荐

发表评论

您必须 [ 登录 ] 才能发表留言!

关注我们的公众号

微信公众号