Dictionary traversal : keywords and corresponding values can be interpreted at the same time using the items() method;
eg:
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
gallahad the pure
robin the brave
Sequence traversal : the index position and corresponding value can be obtained at the same time using the enumerate() function;
eg:
for i,v in enumerate([i for i in range(2,5)]):
print(i,v)
0 2
1 3
2 4
To traverse two or more sequences at the same time , you can use zip() combination;
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.
To traverse a sequence in reverse, first specify the sequence, and then call the reversed() function;
eg:
for i in reversed(range(1, 10, 2)):
print(i)
9
7
5
3
1
To traverse a sequence in order, use the sorted() function to return a sorted sequence without modifying the original value:
eg:
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
apple
banana
orange
pear
str(): Convert dictionaries, tuples, and lists to strings;
eval(): convert string to dictionary, tuple, list
1、简单表达式
print(eval('1+2'))
输出结果:3
2、字符串转字典
print(eval("{'name':'linux','age':18}")
输出结果:{'name':'linux','age':18}
3、传递全局变量
print(eval("{'name':'linux','age':age}",{"age":1822}))
输出结果:{'name': 'linux', 'age': 1822}
4、传递本地变量
age=18
print(eval("{'name':'linux','age':age}",{"age":1822},locals()))
输出结果:{'name': 'linux', 'age': 18}
The zip function for loop uses:
The zip() function in the for loop is used to traverse the list in parallel and output the data
A = ['python','java','c++','abc']
B = ['a','b','c','d']
for i,j in zip(A,B):
print(i,j)
enumerate() function:
The enumerate() function in the for loop is an enumeration function, which is used to combine a traversable data object (such as a list, tuple or string) into an index sequence, and list data and data subscripts at the same time.
A = ['python','java','c++','abc']
for i,val in enumerate(A):
print(i,val)