python - 属性错误 : generator object has no attribute 'sort'

标签 python sorting iterator generator

我有两个文件 .. 我使用循环法从第一个文件中读取一行,从第二个文件中读取第二行。

def roundrobin(*iterables):
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

然后:

c= roundrobin(a, b)

a 和 b 是列表。它如何通过排序进行循环?..我尝试使用

c.sort()

但是错误是

AttributeError: 'generator' object has no attribute 'sort'

我需要根据第一列(d/M/Y)的元素对c进行排序

最佳答案

如错误所示,生成器没有 sort 方法。您可以改为通过内置 sorted 耗尽发电机,它接受一个 iterable 作为输入。这是一个简单的例子:

def randoms(n):
    import random
    for _ in range(n):
        yield random.randint(0, 10)

res = sorted(randoms(10))  # [1, 2, 4, 5, 6, 6, 6, 7, 8, 10]
res = randoms(10).sort()   # AttributeError: 'generator' object has no attribute 'sort'

关于python - 属性错误 : generator object has no attribute 'sort' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52775382/

相关文章:

python - tf.keras model.predict 导致内存泄漏

python - 如何加快我的代码在 NLP 问题中清理文档的速度

java - Java 应用程序中的计数排序和使用

php - PHP 5.3 中的排序($new,SORT_NATURAL | SORT_FLAG_CASE)

linux - Unix/Linux : Sorting by numbers after a comma

java - 迭代器可以防止其 LinkedList 被垃圾收集吗?

python - django-tastypie 能否在单个资源的列表和详细 View 中显示一组不同的字段?

java - Cython/Jython 是一种独立的语言吗?

java - 为什么这段代码会抛出ConcurrentModificationException?

java - 如何在 jsp 页面中传递对象 [s :iterator] to an action class?