我想做一个带有两个列表的for循环,这两个列表中的两个中的较短者只会达到:
list1 = [1, 2, 3]
list2 = ['a', 'b']
for val in (list1 up to length of list2)
print val
Run Code Online (Sandbox Code Playgroud)
输出应该是:
1
2
Run Code Online (Sandbox Code Playgroud)
你可以使用zip():
list1 = [1, 2, 3]
list2 = ['a', 'b']
for a, b in zip(list1, list2):
print(a)
#1
#2
Run Code Online (Sandbox Code Playgroud)
如果您想手动执行此操作,请使用以下命令:
list1 = [1, 2, 3]
list2 = ['a', 'b']
m = min(len(list1), len(list2)) # get the minimum length
for i in range(m):
print(list1[i])
#1
#2
Run Code Online (Sandbox Code Playgroud)
但是,我建议zip(),因为它为你做了一切.能够做某事而不必依赖特殊的编程语言功能是一件好事.