1、以下实例将3X4的矩阵列表转换为4X3列表:
gallahad the pure
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
0 tic
1 tac
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
[[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)gallahad the pure
robin the brave
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
0 tic
1 tac
2 toe
4、同时遍历两个或更多的序列,可以使用 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.