Python3.3.2 官方文档教程---遍历技巧

来源:互联网 发布:编程cs 编辑:程序博客网 时间:2024/05/13 23:36

3.6 遍历技巧

当通过字典遍历数据时,用items()方法就可以同时把关键字和相对应的值从字典中取出。

>>> knights = {gallahadthe purerobinthe brave}

>>> for k, v in knights.items():

... print(k, v)

...

gallahad the pure

robin the brave

 

当用序列遍历数据时,用enumerate()可以同时把位置索引和对应的值得到。

>>> for i, v in enumerate([tictactoe]):

... print(i, v)

...

0 tic

1 tac

2 toe

想要同时遍历两个或多个序列时,可以用方法zip()把属性整合起来。

>>> questions = [namequestfavorite color]

>>> answers = [lancelotthe holy grailblue]

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

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

... print(i)

...

9

7

5

3

1

想要有序的遍历列表,用方法sorted()可以返回一个新的有序列表而不改变原先列表。

>>> basket = [appleorangeapplepearorangebanana]

>>> for f in sorted(set(basket)):

... print(f)

...

apple

banana

orange

Pear

0 0