(100 days, 2 hours, third day) Dictionary traversal

1. When traversing through the dictionary, the keywords and corresponding values ​​can be interpreted simultaneously using the items() method:

t={'a':1,'b':2,'c':3}
for k,v in t.items():
    print(k,v)

  

2. When traversing in the sequence, the index position and corresponding value can be obtained at the same time using the enumerate() function:

t={'a':1,'b':2,'c':3}
for i,v in enumerate(['a','b','c']):
       print(i,v)

  

3. To traverse two or more sequences at the same time, you can use zip() combination:

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

  

4. To traverse a sequence in reverse, first specify the sequence, and then call the reversed() function:

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

  

5. To traverse a sequence in order, use the sorted() function to return a sorted sequence without modifying the original value:

b=['b','k','a','f','g']
for i in sorted(set(b)):
    print(i)

  

Guess you like

Origin blog.csdn.net/zhangxue1232/article/details/109336075