遍历技巧

  • dict.items()

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

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave
  • enumerate()

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

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe
  • zip()

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

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

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

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1
  • sorted()

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

参考资料:https://www.runoob.com/python3/python3-data-structure.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 遍历技巧 在字典中遍历时,关键字和对应的值可以使用items()方法同时解读出来 在序列中遍历时,索引位置和对应值...
    Game0ver阅读 320评论 0 0
  • 最近用python做了一些微小的工作,跟pymysql库打了些交道,其中大概是由于自身的强迫症,踩了一些坑。坑并不...
    PhilicX阅读 858评论 0 5
  • abs() 函数 描述 abs() 函数返回数字的绝对值。 语法 以下是 abs() 方法的语法: abs( x ...
    时光是座城阅读 510评论 0 2
  • # Python关键字 部分单词没有分类整理按照顺序整理的 ``` statements语句 print输出 qu...
    ZhouLang阅读 612评论 0 0
  • 他原来只是一个普普通通的耋耄老人,却可以在镜头下这么优雅。 阳光下满是悠然自得的神情,镜框后透着幸福的眼神,精致得...
    桃之夭夭echo阅读 243评论 0 0