[英]find second largest number from list using for loop with python
当我运行代码时,它返回 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)
一旦你有了一个新的最大值,只需将旧的最大值推到第二个最大值
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)
尝试这个:
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)
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
保留,直到x > max
时被x
替换。 每当更新max
时,技术上second_last
也应该更新,因为旧的max
是新的second_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)
此外,最好不要假设列表是非空的。
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)
您可以构建一个包含 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: list
和max
是 Python 内置的,不要将它们用作变量名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.