【问题标题】:Set the index of a Python array设置 Python 数组的索引
【发布时间】:2013-03-27 07:47:29
【问题描述】:

我正在尝试在 Python 中设置数组的索引,但它没有按预期运行:

theThing = []
theThing[0] = 0
'''Set theThing[0] to 0'''

这会产生以下错误:

Traceback (most recent call last):
  File "prog.py", line 2, in <module>
    theThing[0] = 0;
IndexError: list assignment index out of range

在 Python 中设置数组索引的正确语法是什么?

【问题讨论】:

  • 这里在ideone上,同样的错误:ideone.com/0IV1Sc#view_edit_box
  • theThing = [] 创建一个空数组,因此索引 0 不存在。
  • 我对 Python 比较陌生(来自 JavaScript 背景),所以我觉得这很令人惊讶。在 JavaScript 中,您可以简单地使用 var theThing = new Array(); theThing[0] = 0;theThing 的第 0 个元素设置为 0。
  • 代替theThing[0]=0,试试theThing.append(0)
  • 原来在Python中初始化一个特定大小的数组其实是可以的:stackoverflow.com/questions/6142689/…

标签: python


【解决方案1】:

Python 列表没有固定大小。要设置0th 元素,您需要拥有一个0th 元素:

>>> theThing = []
>>> theThing.append(12)
>>> theThing
[12]
>>> theThing[0] = 0
>>> theThing
[0]

JavaScript 的数组对象与 Python 的有点不同,因为它会为您填充以前的值:

> x
[]
> x[3] = 5
5
> x
[undefined × 3, 5]

【讨论】:

  • theThing.append(12) 对这里的数组有何影响?
  • theThing.append(12) 在(当前为空)数组的末尾添加一个 12。
  • @AndersonGreen:列表为空,因此没有0th 元素。我刚刚添加了.append(12) 来给出列表之一。 JavaScript 的语法可能会让你失望。
  • 是否可以初始化一个特定大小的空数组,然后(例如,一个长度为 10 的空数组?)
  • @AndersonGreen:不是这样。您可以使用thing = [None for i in range(10)],但列表仍将包含 10 个元素。
【解决方案2】:

这取决于你真正需要什么。首先你必须read python tutorials about list. 在你的情况下,你可以像这样使用:

lVals = [] 
lVals.append(0)
>>>[0]
lVals.append(1)
>>>[0, 1]
lVals[0] = 10
>>>[10, 1]

【讨论】:

    【解决方案3】:

    您正在尝试分配一个不存在的职位。如果要向列表中添加元素,请执行

    theThing.append(0)
    

    如果你真的想分配给索引 0,那么你必须首先确保列表非空。

    theThing = [None]
    theThing[0] = 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 2021-12-31
      • 1970-01-01
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      相关资源
      最近更新 更多