简体   繁体   English

收益率合并排序函数中的错误

[英]Error in Merge Sort function in yield

I received a merge sort function from someone else, here's the code:我从其他人那里收到了一个合并排序功能,这是代码:

def mergesort(lst):
    l = len(lst)
    if l <= 1:
        return lst
    return mergesorted(mergesort(lst[:l//2]), mergesort(lst[l//2:]))

def mergesorted(a, b):
    i, j = 0, 0
    la, lb = len(a), len(b)
    while i < la or j < lb:
        if i == la or (j != lb and a[i] > b[j]):
            yield b[j]
            j += 1
        else:
            yield a[i]
            i += 1

I'm still trying to understand how yield works, so when I was trying to print the result to test the function, I used我仍在尝试了解 yield 的工作原理,因此当我尝试打印结果以测试函数时,我使用了

m = mergesort([4, 2, 5, 1, 6, 3])

for i in m :
    print(i)

It gave me this error:它给了我这个错误:

Traceback (most recent call last):
    for i in m :
    la, lb = len(a), len(b)
TypeError: object of type 'generator' has no len()

Am I using the print statement wrong?我使用的打印语句错误吗?

The fact that mergesorted has the yield keyword in it means that it's a generator. mergesorted包含yield关键字的事实意味着它是一个生成器。 And like the error message says, generators don't have a len method.就像错误消息所说的那样,生成器没有len方法。
The reason that generators don't have a len method is because generators don't actually know what values they're going to yield, until it's time to yield them.生成器没有len方法的原因是因为生成器实际上并不知道它们将产生什么值,直到是时候产生它们。 Unlike objects like list s or tuple s.不像list s 或tuple s 之类的对象。
In this case, I don't see any advantage to using yield instead of return .在这种情况下,我认为使用yield而不是return没有任何优势。

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

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