遍历技巧

limalove / 2023-09-03 / 原文

菜鸟教程:https://www.runoob.com/python3/python3-data-structure.html

链接

 

 

 1 # 在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来:
 2 knights = {'gallahad': 'the pure', 'robin': 'the brave'}
 3 for k, v in knights.items():
 4     print(k, v)
 5     
 6     
 7     
 8 # 在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到:    
 9 for i, v in enumerate(['tic', 'tac', 'toe']):
10     print(i, v)
11 
12 
13 # 同时遍历两个或更多的序列,可以使用 zip() 组合:
14 questions = ['name', 'quest', 'favorite color']
15 answers = ['lancelot', 'the holy grail', 'blue']
16 for q, a in zip(questions, answers):
17     print('What is your {0}?  It is {1}.'.format(q, a))
18 
19 
20 
21 # 要反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数:
22 for i in reversed(range(1, 10, 2)):
23     print(i)
24     
25     
26 # 要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:  
27 basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
28 for f in sorted(set(basket)):
29     print(f)