【问题标题】:Python: Why does this array get 'gridwidth' amount of indices?Python:为什么这个数组会获得“gridwidth”数量的索引?
【发布时间】:2020-04-04 08:10:10
【问题描述】:
for i in range(0, gridwidth):
        row.append(random.randint(0, 1))

由于数组索引从 0 开始,我假设 row 数组将具有 gridwidth + 1 索引,因为它会计算每个整数,包括 gridwidth,但也包括 0。但是,在检查数组后,它仅包含 gridwidth 数量的索引。虽然它不会妨碍我的代码,但我很好奇为什么会发生这种情况。

【问题讨论】:

    标签: python arrays indexing


    【解决方案1】:

    虽然它不会妨碍我的代码,但我很好奇为什么会发生这种情况。

    嗯,你做了以下假设:

    因为它会计算每个整数,直到并包括网格宽度,但也包括 0。

    您是否尝试测试该假设?

    for i in range(0, gridwidth):
        print(i)
    

    注意gridwidth 的值没有打印出来。

    或者您可以尝试阅读文档:

    >>> help(range)
    Help on class range in module builtins:
    
    class range(object)
     |  range(stop) -> range object
     |  range(start, stop[, step]) -> range object
     |
     |  Return an object that produces a sequence of integers from start (inclusive) |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
     |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
     |  These are exactly the valid indices for a list of 4 elements.
     |  When step is given, it specifies the increment (or decrement).
    

    发生这种情况的原因是因为 range 就是这样定义的。

    以这种方式定义range 的动机是因为这是程序员所习惯的——因为在旧语言中,您可以在循环中对数组进行索引(而不是直接获取项目),easier to avoid logical errors 就是这种方式。

    【讨论】:

      【解决方案2】:

      如果你真的很好奇,试试这个:

      print(len(range(0, gridwidth)))
      

      然后,看看range() 文档,

      范围 r 的内容由公式 r[i] = start + step*i 确定,其中 i >= 0 和 r[i]

      range(0, gridwidth)(范围是一类不可变的可迭代对象)将返回一个数字从 0 到 (gridwidth - 1) 的序列。

      for i in range(0, 5):
          print(i)
      

      输出:

      0
      1
      2
      3
      4
      

      【讨论】:

        【解决方案3】:

        那是因为range 函数在左侧关闭,在右侧打开。这意味着它将包括0,但不包括gridwidth。数学符号是 [0, gridwidth)。所以你的迭代来自0 togridwidth-1making array containgridwidth`元素。

        【讨论】:

          【解决方案4】:

          您的for 循环将迭代gridwidth 次,因此您的row 将附加gridwidth 元素,您也可以注意内置类range,它会为您提供迭代次数您的for 循环,范围将为您提供0gridwidth - 1 之间的数字

          另外,range(0, gridwidth)range(gridwidth) 相同,range 的起点默认为0

          如果你想实现gridwidth + 1 元素附加到你的row 你可以使用:

          for i in range(gridwidth + 1):
                  row.append(random.randint(0, 1))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-12-23
            • 1970-01-01
            • 2017-02-14
            • 2017-10-05
            • 2021-12-04
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多