2017-02-12 55 views
1

下面的代碼是爲了列出兩個列表中相同索引位置中較大的數字。 如何使用重寫此代碼,而使用循環代替代替循環?在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] 

回答

1

使用ziplist 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 
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 
2

您可以使用pop()爲了每次直到ab船尾兩個列表的第一項爲真值(它包含的項目):

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] 
0

你可以試試這個:

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

您也可以嘗試用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]