【问题标题】:TypeError: 'int' object is not iterable after using sorted function (python 2.7)TypeError:“int”对象在使用排序函数后不可迭代(python 2.7)
【发布时间】:2018-08-03 01:10:48
【问题描述】:

所以我正在编写这段代码来查看是否可以删除列表中的元素以使列表增加。 在下面的代码中为什么会出现这个错误?

def almostIncreasingSequence(sequence):
    sorted_sequence = sorted(sequence)
    counter = 0
    for i in len(sequence):
        if sorted_sequence[i] != sequence[i]:
            counter += 1
    if counter > 1:
        return True
    else:
        return False

【问题讨论】:

  • 再看for i in len(sequence)len(sequence) 是一个数字。你的意思可能是range(len(sequence))

标签: python python-2.7 int iterable


【解决方案1】:

len(sequence)这里是数字,不能迭代数字:

for i in len(sequence):
    ...

你可能想要

for a,b in zip(sequence, sorted_sequence):
    ...

您也可以返回计数而不是布尔值,或者从 for 循环中返回,因为不需要遍历整个序列来检查该计数是否 > 1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-06
    • 2013-10-31
    • 2020-06-10
    • 2016-02-24
    • 1970-01-01
    • 2017-09-11
    相关资源
    最近更新 更多