Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用累积函数对列表排序(高阶函数)_Python - Fatal编程技术网

Python 使用累积函数对列表排序(高阶函数)

Python 使用累积函数对列表排序(高阶函数),python,Python,使用accumulate我想写一个排序函数 def accumulate(fn, initial, seq): if seq == (): return initial else: return fn(seq[0], accumulate(fn, initial, seq[1:])) 这是我的代码,我似乎无法运行它。为什么? def insertion_sort_hof(tup): return accumulate(lambda x,y

使用
accumulate
我想写一个排序函数

def accumulate(fn, initial, seq):
    if seq == ():
        return initial
    else:
        return fn(seq[0], accumulate(fn, initial, seq[1:]))
这是我的代码,我似乎无法运行它。为什么?

def insertion_sort_hof(tup):
    return accumulate(lambda x,y: x,y = y,x if x > y else None  , () ,tup)

lambda不能包含赋值,因此lambda无效。尝试添加这样的括号,您将得到一条错误消息:

insertion_sort_hof(()) # ()
insertion_sort_hof((19,10,1,4,3,1,3, 2))  #(1, 1, 2, 3, 3, 4, 10, 19)

而且它无论如何都不起作用,因为您只能在本地将值交换到该函数。

它怎么不起作用?你会遇到什么错误?
我似乎无法运行它。
你是什么意思?你调用函数了吗?关键字argTypeError之后是非关键字arg:unorderable types:int()>tuple(),nope不能像我说的那样工作。你的整个方法都有缺陷。需要重新考虑。@user3398505“无序类型”错误意味着您正在尝试对没有内在顺序的数据进行排序,即先出现什么,数字
0
['hat','balloon']
?当你看到这一点时,你必须问自己“我想做什么?”因为你的输入数据是不一致的。
def accumulate(fn, initial, seq):
    if seq == ():
        return initial
    else:
        return fn(seq[0], accumulate(fn, initial, seq[1:]))