*之后的参数必须是可迭代的,而不是int

分数

我有一个小的脚本,它包含一个列表和一个值,该值表示将列表分成多少大小的子列表:

def chunk(alist, n):
    i = 0
    j = n
    while j < (len(alist) + 2):
        sub = alist[i:j]
        i += n
        j += n
        print(sub)

chunk([1, 2, 3, 4, 5], 2)

这有效。我得到[1,2] [3,4] [5]

但是,如果我尝试从函数返回sub并在循环中将其打印出来,它将失败:*之后的参数必须是可迭代的,而不是int

def chunks(alist, n):
    i = 0
    j = n
    while j < (len(alist) + 2):
        sub = alist[i:j]
        i += n
        j += n
        return sub

for chunk in chunks([1, 2, 3, 4, 5], 2):
    print(*chunk)

sub是一个可迭代的(列表)。不知道我在做什么错。

注意不能使用itertools或任何其他附件。

吹牛

您的sub变量仅包含列表的一部分。相反,应将其作为chunks函数的返回值附加到列表列表中

def chunks(alist, n):
    i = 0
    j = n
    output = []
    while j < (len(alist) + 2):
        output.append(alist[i:j])
        i += n
        j += n
    return output

for chunk in chunks([1, 2, 3, 4, 5], 2):
    print(*chunk)

输出:

1 2
3 4
5

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

*之后的_reverse_with_prefix()参数必须是可迭代的,而不是int

*之后的add()参数必须是可迭代的,而不是int Pygame

*之后的/ polls / 1 / vote / _reverse_with_prefix()参数处的Django TypeError必须是可迭代的,而不是int

类型错误:* 后的 start() 参数必须是可迭代的,而不是 int

*之后没有通过render()参数传递的参数必须是可迭代的,而不是pygame.Surface

“* 之后的浮动对象参数必须是可迭代的,而不是浮动的”不知道我做错了什么

线程 thread-2 中的异常,TypeError:* 之后的 clickc() 参数必须是可迭代的,而不是 bool

Python线程错误-必须是可迭代的,而不是int

int 不是可迭代的 python

*之后的add()参数必须是序列,而不是设置

Django rest框架`TypeError:**之后的类型对象参数必须是一个映射,而不是被抛出的int`

TypeError:'int'对象不是可迭代的Python?

int对象不是可迭代的python

获取'int'对象不是可迭代的错误

**之后的MetaSerialisable对象参数必须是映射,而不是unicode

“int”对象不是可迭代的错误?怎么修?

MysqlDB调用TypeError:'int'对象不是可迭代的python

'int'对象不是可迭代的python暴力密码

类型错误:Int对象不是可迭代错误[For循环]

TypeError:“ int”对象不是可迭代的Python读取文件

在 KERAS 中检索“int”对象不是可迭代错误的问题

类型错误:super() 参数 1 必须是类型,而不是 int (Python)

int()函数参数必须是字符串或数字,而不是“元组”

类型错误:write() 参数必须是 str,而不是 int 问题

所谓的“可迭代”不是

“int”类型的参数不需要可迭代的帮助

为什么解压缩此地图对象的打印内容“必须是可迭代的,而不是地图”?

熊猫drop_duplicates-TypeError:*之后的类型对象参数必须是序列,而不是映射

TypeError:**之后的jsonify()参数必须是映射,而不是使用Flask返回JSON的列表