【问题标题】:Python Function with Lists and Sets带有列表和集合的 Python 函数
【发布时间】:2015-07-10 21:09:41
【问题描述】:

所以我试图找出这个问题,但我不知道为什么它不起作用。

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

我的代码:

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__'

谢谢!

【问题讨论】:

    标签: python list function set


    【解决方案1】:
    list_copy2 = list_copy2.sort()
    

    .sort() 对列表进行就地排序并返回None。因此,您正在对列表进行排序,然后将其丢弃。你想要的只是:

    list_copy2.sort()
    

    或者:

    list_copy2 = sorted(list_set)
    

    sorted 始终返回一个列表,因此您可以使用它对集合进行排序并一步将其转换为列表!

    【讨论】:

    • 对不起,我读错了你说的@kindall。我读得有点快
    【解决方案2】:

    您需要使用sorted 而不是sortsorted 返回一个新列表,即原始列表的排序版本。 sort 将对列表进行就地排序,并在这样做时返回 None

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

    【讨论】:

      【解决方案3】:

      求助,我不能使用 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-03
        • 2016-07-22
        • 1970-01-01
        • 2020-08-07
        相关资源
        最近更新 更多