[英]I'm trying simplify my code but the answer is wrong
This is my code (It's right): 这是我的代码(正确):
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
l = list(set(sorted(arr)))
l.remove(max(l))
print(max(l))
But I want do this (pythonic): 但我想这样做(pythonic):
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
l = list(set(sorted(arr)))
print(l.remove(max(l)))
So.. when I do this my code just print: 所以..当我这样做时,我的代码只是打印:
print(l.remove(max(l)))
打印(l.remove(max(l)))
None
没有
What's the problem? 有什么问题? I just want simplify my code.
我只想简化我的代码。
The task: I've a list and I want print the second maximum score. 任务:我有一个列表,我想打印第二个最高分。
Take a look at the documentation . 看一下文档 。 The
list.remove
method is one that modifies the list in-place . list.remove
方法是一种就地修改列表的方法。 That is to say, it modifies the list that you call it on, instead of returning a new one with the change you want. 也就是说,它修改了您调用它的列表,而不是返回您想要的更改的新列表。
Since this function returns nothing, printing l.remove()
gives you "None". 由于此函数不返回任何内容,因此打印
l.remove()
您“无”。 To print the list with the element removed, you'll have to stick with your original code. 要在移除元素的情况下打印列表,您必须坚持原始代码。
Convert the map object to a set with set()
, convert to sorted list with sorted()
and take the second last element with [-2]
: 使用
set()
将地图对象转换为集合,使用sorted()
将其转换为排序列表,并使用[-2]
倒数第二个元素:
print(sorted(set(arr))[-2])
In my opinion, this is more Pythonic than removing the max and then printing the new max as it is clearer and achieved in less steps. 我认为,这比删除最大值然后打印新的最大值更清晰,并且可以用更少的步骤实现,因此比Python具有更多的Python风格。
You should use a heap instead of sorting. 您应该使用堆而不是排序。 You can build a heap in O(n) time and return the
k
th largest item (for any constant k
) in O(n) time as well; 您可以在O(n)时间建立一个堆,并在O(n)时间返回第
k
个最大项(对于任何常数k
); sorting takes O(n lg n) time. 排序需要O(n lg n)的时间。
import heapq
n = int(input())
arr = [int(x) for x in input.split()]
heapq.heapify(arr) # In-place; does not return the heapified list.
print(heapq.nlargest(2, arr)[-1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.