列表中的第二个最小元素

时间:2017-05-17 04:21:43

标签: python list

我必须找到成绩第二低的学生的姓名。我的代码在一些测试用例中运行良好,但是这个特别令我感到不安:

  

4   雷切尔   -50   莫尔   -50   辛   -50   沙欣   51

返回的输出是

  

莫尔   雷切尔   光泽

Shaheen排名第二,应该是输出。我不知道我哪里错了。另外,我在等级作为浮动输入时遇到问题:

  

4   Shadab   8   Varun的   8.9   Sarvesh   9.5   苛刻   10

抛出的输出是Sarvesh,应该是Varun。

import heapq
# range(int(input())):
n = int(input())
builtlist = []
temp= []
names = []
for i in range(0, n):
name = input()
score = float(input())
builtlist.append([name, score])

temp = sorted(builtlist, key = lambda x: x[1])
#minvalue = min(temp, key= lambda x: x[1])

for j in range(len(temp)):
secondsmall = heapq.nsmallest(2, temp)[-1]
if (temp[j][1]==secondsmall[1]):
    names.append(temp[j][0])
list = sorted(names)
print(*list, sep = "\n")

我想我使用的heapq.nsmallest方法有些麻烦,但我无法弄清楚它是什么。

4 个答案:

答案 0 :(得分:1)

你错了temp = sorted(builtlist, key = lambda x: x[1])heapq.nsmallest(2,temp)返回temp中的n个最小元素,在您的情况下,它将为[50,50,50,51],因此它将返回[50, 50] 使用temp = list(set(temp))然后您的代码就可以使用。

如果您不想使用heapq,可以使用此代码获得相同的答案。

# range(int(input())):
n = int(input())
builtlist = []
temp= []
names = []
for i in range(0, n):
    name = input()
    score = float(input())
    builtlist.append([name, score])

temp = list(set([x[1] for x in builtlist]))
secondsmall = sorted(temp)[1]

for j in range(len(builtlist)):
    if (builtlist[j][1]==secondsmall):
        names.append(builtlist[j][0])
list_print = sorted(names)
print(*list_print, sep = "\n")

答案 1 :(得分:0)

这里有很多事情要发生。

首先,调试代码不存在stackoverflow,这是对网站的误用。请将来不要这样做,并注意

code tags.

其次,heapq.nsmallest()将返回最小元素请求的数量。如果两个元素最少并且共享一个值,那么它们都将被返回。因此代码按预期运行。

我会研究这个问题的python词典和hashsets。有一个更优雅的解决方案。

答案 2 :(得分:0)

不需要使用var questions = [ { text:"Which picture shows the church?", answers: [ { image: "", comment: "", points: 1 }, { image: "", comment: "", points: 1 }, { image: "", comment: "", points: 1 } ] }, { text:"Which picture shows the house?", answers: [ { image: "", comment: "", points: 1 }, { image: "", comment: "", points: 1 }, { image: "", comment: "", points: 1 } ] } ];

heapq

答案 3 :(得分:0)

Python中heapq的一个更常见的对应点是Counter

import collections as ct

def second_smallest(lst):
    """Return the second smallest entry."""
    c = ct.Counter()
    for name, score in lst:
        c.update({name:score})
    return c.most_common()[-2]

应用:

builtlist = [["Rachel", -50], ["Mawer", -50], ["Sheen", -50],["Shaheen", 51]]
second_smallest(builtlist)
# ('Sheen', -50)

builtlist = [["Shadab", 8], ["Varun", 8.9], ["Sarvesh", 9.5], ["Harsh", 10]]
second_smallest(builtlist)
# ('Varun', 8.9)

Here are ways使用Counter.most_common()方法获取最不常见(或最小)的值。