下面的代碼是爲了列出兩個列表中相同索引位置中較大的數字。 如何使用重寫此代碼,而使用循環代替代替循環?在python中使用while循環比較列表
a = [7,12,9,14,15,18,12]
b = [9,14,8,3,15,17,15]
big = []
for i in range(len(a)):
big.append(max(a[i],b[i]))
print(big)
[9, 14, 9, 14, 15, 18, 15]
下面的代碼是爲了列出兩個列表中相同索引位置中較大的數字。 如何使用重寫此代碼,而使用循環代替代替循環?在python中使用while循環比較列表
a = [7,12,9,14,15,18,12]
b = [9,14,8,3,15,17,15]
big = []
for i in range(len(a)):
big.append(max(a[i],b[i]))
print(big)
[9, 14, 9, 14, 15, 18, 15]
使用zip
和list comprehension
:
a = [7, 12, 9, 14, 15, 18, 12]
b = [9, 14, 8, 3, 15, 17, 15]
big = [max(t) for t in zip(a, b)]
使用while
:
a = [7, 12, 9, 14, 15, 18, 12]
b = [9, 14, 8, 3, 15, 17, 15]
big = []
i = 0
while i < len(a):
big.append(max(a[i], b[i]))
i += 1
一種方法是用這個當
a = [7, 12, 9, 14, 15, 18, 12]
b = [9, 14, 8, 3, 15, 17, 15]
big = []
i = 0
while i < len(a):
big.append(max(a[i], b[i]))
i += 1
print big
您可以使用pop()
爲了每次直到a
或b
船尾兩個列表的第一項爲真值(它包含的項目):
In [15]: while a:
big.append(max(a.pop(0),b.pop(0)))
....:
In [16]: big
Out[16]: [9, 14, 9, 14, 15, 18, 15]
你可以試試這個:
a = [7,12,9,14,15,18,12]
b = [9,14,8,3,15,17,15]
big = []
i=0
while i<len(a):
if a[i]<b[i]:
big.append(b[i])
i+=1
else:
big.append(a[i])
i+=1
print(big)
您也可以嘗試用zip()
和列表理解,像這樣:
a = [7,12,9,14,15,18,12]
b = [9,14,8,3,15,17,15]
big = [max(c) for c in zip(a,b)]
print big
輸出:
[9, 14, 9, 14, 15, 18, 15]