简体   繁体   English

python:当最小元素数大于1时列表中的第二个最小值

[英]python: second smallest value in list when number of smallest elements is greater than 1

the following code returns the second smallest value only when the elements in the list are different from each other, but in this case, since '1' appears twice, the second smallest printed number is still '1'.以下代码仅在列表中的元素彼此不同时才返回第二小的值,但在这种情况下,由于 '1' 出现了两次,所以第二小的打印数字仍然是 '1'。 How to fix this issue?如何解决这个问题?

l=[1,2,1,3,4,5,6,2,7]
print(sorted(l)[1])

This is not the most efficient method, but much quicker than sorting a set:这不是最有效的方法,但比对集合排序要快得多:

l=[1,2,1,3,4,5,6,2,7]
min1 = min(l)
min2 = min(i for i in l if i > min1)
print(sorted(list(set(l)))[1])

你必须摆脱重复

You can use a set to get only the unique elements of your list.您可以使用set来仅获取列表中的唯一元素。 Then you sort the set and get the element on index 1.然后对集合进行排序并获取索引 1 上的元素。

l = [1, 2, 1, 3, 4, 5, 6, 2, 7]
sorted(set(l))[1]
>> 2
l=[1,2,1,3,4,5,6,2,7]
min = 100
sub_min = 100
for i in range(len(l)):
    if l[i] < min:
        min = l[i]
    if l[i] < sub_min and l[i] > min:
        sub_min = l[i]
# print(min, sub_min)

This might seem crude, but if you don't want to use the 'sorted' method and need a linear runtime, you can use this.这可能看起来很粗糙,但是如果您不想使用 'sorted' 方法并且需要线性运行时,您可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM