剪切方法脚本类型错误:“generator”类型的对象没有len()

2024-10-03 06:29:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python编写一个简单的剪切方法(Wikipedia)脚本,但遇到了一些麻烦。我得到的是:

import random

def splitter(string, num):
    pieces = string.split()

    for i in xrange(0, len(pieces), num):
        yield' '.join(pieces[i:i+num])

def cutup(what, order):
    mixed = list(random.shuffle(splitter(what, order)))
    for piece in mixed:
        print piece + " "

cutup(range(1,100), 3)

其思想是将输入分成num长的单词块,将这些单词块无序排列,拼接在一起,然后将它们吐出来。但我一直收到这样的错误:

^{pr2}$

我认为这与random.shuffle()返回生成器有关?我好像修不好。有什么想法吗?在


Tags: inforstringpiecedeforderrandom单词
1条回答
网友
1楼 · 发布于 2024-10-03 06:29:03

random.shuffle()需要知道输入的长度(并尝试获取对象的长度)。生成器无法提供此功能,您必须将其具体化为一个列表:

lst = list(yielding(x))
random.shuffle(lst)

另外,请注意,random.shuffle进行就地列表修改。 文档是here。在

相关问题 更多 >