當我運行代碼時,它回傳 9 但答案應該是 10
list = [9, 6, 4, 10, 13, 2, 3, 5]
max = list[0]
second_last = list[0]
for x in list:
if x > max:
max = x
# Here is an issue with this statement
if x > second_last and x != max:
second_last = x
print(second_last)
uj5u.com熱心網友回復:
一旦你有了一個新的最大值,只需將舊的最大值推到第二個最大值
list = [9, 6, 4, 10, 13, 2, 3, 5]
max = float('-inf')
second_last = float('-inf')
for x in list:
if x > max:
second_last = max
max = x
elif x > second_last and x != max:
second_last = x
print(second_last)
uj5u.com熱心網友回復:
x: max and second_last
9: 9 and 9
6: 9 and 9
4: 9 and 9
10: 10 and 9
13: 13 and 9 <<<
2: 13 and 9
3: 13 and 9
5: 13 and 9
您實際上是在丟失有關的資訊second_last,這些資訊一直保留到何時max被替換。無論何時更新,技術上也應該更新,因為舊的就是新的。xx > maxmaxsecond_lastmaxsecond_last
請注意,如果滿足第一個if陳述句,則不能滿足第二個陳述句,因此max和second_last永遠不會同時更新。
因此,除非y在迭代中有一些值,例如second_last < y != max- 例如:list = [9, 12, 10],y = 10-,否則您的代碼將產生不正確的輸出。second_last因此,當序列嚴格增加時,您的代碼永遠不會更新。
這是您的代碼的修復:
list = [9, 6, 4, 10, 13, 2, 3, 5]
max = list[0]
second_last = list[0]
for x in list:
if x > max:
second_last = max # add this line
max = x
elif x > second_last and x != max:
second_last = x
print(second_last)
此外,最好不要假設串列是非空的。
uj5u.com熱心網友回復:
試試這個:
l = [9, 6, 4, 10, 13, 2, 3, 5]
_max = max(l)
_second = min(l)
for num in l:
if _second < num < _max:
_second = num
print(_second)
uj5u.com熱心網友回復:
list = [9, 6, 4, 10, 13, 2, 3, 5]
max = list[0]
second_last = list[0]
for x in list[1:]:
if x > max:
second_last = max
max = x
elif x < max and x > second_last:
second_last = x
print(second_last)
uj5u.com熱心網友回復:
您可以構建一個包含 2 個元素(max和second_last)的新串列:
lst = [9, 6, 4, 10, 13, 2, 3, 5]
# results[0] = max; results[1] = second_last
results = [float("-inf"), float("-inf")] # initialise negative infinite!
for item in lst:
if item > results[0]:
results = [item, results[0]]
print(results)
# OR
max_value, second_last = results
print(max_value)
print(second_last)
出去:
[13, 10]
13
10
最簡單的方法是使用內置排序:
results = sorted(lst, reverse=True)
print(results[:2])
>>> [13, 10]
Node: listandmax是 Python 內置的,不要將它們用作變數名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/424730.html
標籤:Python python-3.x 列表 for循环
