为 + 请求不支持的操作数类型:'range' 和 'list'

Asking for unsupported operand type(s) for +: 'range' and 'list'

我正在尝试 运行 以下代码,但出现错误。以下代码是使用 Spyder 的 运行 for Python3。

def create_batches(data_size, batch_size, shuffle=True):
    """create index by batches."""
    batches = []
    ids = range(data_size)
    if shuffle:
        random.shuffle(ids)
    for i in range(data_size // batch_size):
        start = i * batch_size
        end = (i + 1) * batch_size
        batches.append(ids[start:end])
    # the batch of which the length is less than batch_size
    rest = data_size % batch_size
    if rest > 0:
         batches.append(ids[-rest:] + [-1] * (batch_size - rest))  # -1 as padding
    return batches

错误是:

TypeError: unsupported operand type(s) for +: 'range' and 'list'

有谁知道如何解决这个问题?

random.shuffle() 仅适用于 可变序列 ,通常是 list 对象。 range() 生成一个 不可变的 序列对象,random.shuffle() 不能在一个范围内移动值。

首先将范围转换为列表:

ids = list(range(data_size))

在 Python 2 中,range() 用于生成整数列表(相对于 xrange(),生成不可变序列),因此您仍然可以在网上找到使用 range() 洗牌前没有 list()。在尝试使在线代码示例适应 Python 3 时考虑到这一点。另请参阅 NameError: global name 'xrange' is not defined in Python 3