栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python之遍历技巧

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python之遍历技巧

字典遍历:关键字和对应的值可以使用 items() 方法同时解读出来;

eg:

knights = {'gallahad': 'the pure', 'robin': 'the brave'}

for k, v in knights.items():

    print(k, v)

gallahad the pure
robin the brave

序列遍历:索引位置和对应值可以使用 enumerate() 函数同时得到;

eg:

for i,v in enumerate([i for i in range(2,5)]):

    print(i,v)

0 2
1 3
2 4

同时遍历两个或更多的序列,可以使用 zip() 组合;

eg:

questions = ['name', 'quest', 'favorite color']

answers = ['lancelot', 'the holy grail', 'blue']

for q, a in zip(questions, answers):

    print('What is your {0}?  It is {1}.'.format(q, a)) 

What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数;

eg:

for i in reversed(range(1, 10, 2)):

    print(i)

9
7
5
3
1

要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:

eg:

basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

for f in sorted(set(basket)):

     print(f)

apple
banana
orange
pear

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648794.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号