【问题标题】:How to create a function in Python to determine if list is sorted or not?如何在 Python 中创建一个函数来确定列表是否已排序?
【发布时间】:2020-02-23 04:54:13
【问题描述】:

我被要求检查是否使用函数对列表进行了排序,但是我在不使用输入函数的情况下在函数中定义参数 (lst) 时遇到了麻烦。它说 lst 是未定义的,但我不确定如何在不使用输入函数的情况下更改它

def is_sorted(lst):
    lst  = []
    flag = 0
    lst1 = lst[:]
    lst1.sort()
    if (lst1 == lst):
        flag = 1
    if (flag) :
        return "True"
    else:
        return "False"

print (is_sorted(lst))

错误是lst没有定义

【问题讨论】:

  • 在你第一次调用lst 时(在print (is_sorted(lst)) 行中)你实际上并没有给lst 一个值。在print() 之前,您需要一个lst = [1,2,3](或其他东西)
  • 只是指出 - 这个函数将始终返回“真”,因为参数 lst 将被覆盖并成为一个空列表。

标签: python python-3.x function sorting


【解决方案1】:

在您第一次调用lst 时(在print (is_sorted(lst)) 行中),您实际上并没有给lst 一个值。在 print() 之前,您需要一个 lst = [1,2,3](或其他东西)。

但是,您可能想多了这个功能。我添加了一个简化版本,使用 Python 的 sorted 函数作为比较器。

def is_sorted(lst):
    if (lst == sorted(lst)) or (lst == sorted(lst, reverse = True)):
        return "True"
    else:
        return "False"

lst = [3,1,2]
print (is_sorted(lst))
lst = [1,2,3]
print (is_sorted(lst))
lst = [3,2,1]
print (is_sorted(lst))

输出:

False
True
True

【讨论】:

    【解决方案2】:

    为了理解错误,必须理解函数的参数和参数之间的区别。

    有用的材料:

    Python 词汇表:parameterargument

    Python 常见问题解答:What is the difference between arguments and parameters

    【讨论】:

      猜你喜欢
      • 2012-09-24
      • 1970-01-01
      • 2011-03-04
      • 2015-02-20
      • 2015-03-16
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多