JavaEar 专注于收集分享传播有价值的技术资料

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

I am trying to run the following code but there was an error. The following code was run in for Python3 using Spyder.

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

The errror was:

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

Does anyone know how to solve this problem?

1个回答

    最佳答案
  1. random.shuffle() only works on mutable sequences, which is usually a list object. range() produces an immutable sequence object, random.shuffle() can't move the values in a range around.

    Convert the range to a list first:

    ids = list(range(data_size))
    

    In Python 2, range() used to produce a list of integers (vs. xrange(), producing the immutable sequence), so you can still find code online that uses range() without list() before shuffling. Take this into account when trying to adapt online code examples to Python 3. Also see NameError: global name 'xrange' is not defined in Python 3