Python 列表和集合函数

Python Function with Lists and Sets

所以我试图找出这个问题,但我无法弄清楚为什么它不起作用。

前提是给你一个输入列表,你要找到倒数第二小的值。该列表可以有任意数量的整数并且可以重复值;您无法更改列表。

我的代码:

def second_min(x):
    input_list = list(x)
    print input_list
    list_copy = list(input_list)
    list_set = set(list_copy)
    if len(list_set) > 1:
        list_copy2 = list(list_set)
        list_copy2 = list_copy2.sort()
        return list_copy2[1]
    else:
        return None

print second_min([4,3,1,5,1])
print second_min([1,1,1])

这两个输入的输出是:

3
None

它在第 9 行和第 13 行给我错误。

TypeError: 'NoneType' object has no attribute '__getitem__'

谢谢!

list_copy2 = list_copy2.sort()

.sort() 对列表进行原位排序,returns None。因此,您正在对列表进行排序,然后将其丢弃。您只需要:

list_copy2.sort()

或:

list_copy2 = sorted(list_set)

sorted总是returns一个列表,所以你可以用它来对集合进行排序并一步到列表!

您需要使用 sorted 而不是 sortsorted returns 一个新列表,即原始列表的排序版本。 sort 将就地排序列表,returns None 这样做。

def second_min(x):
    if len(x) > 1:
        return sorted(x)[1]
    else:
        return None

>>> second_min([4,3,1,5,1])
1

求助,我不会用sorted!不允许!

def second_min(li):
    if len(li) < 2:
        return None
    it = iter(li)
    a, b = next(it), next(it)
    next_lowest, lowest = max(a, b), min(a, b)
    for x in it:
        if x < next_lowest:
            if x < lowest:
                lowest, next_lowest = x, lowest
            else:
                next_lowest = x
    return next_lowest