【问题标题】:How can I solve the error: 'int' object does not support item assignment如何解决错误:“int”对象不支持项目分配
【发布时间】:2021-10-29 03:49:30
【问题描述】:
def foo(x, a, b, i, j):
    k = j
    ct = 0
    while k > i-1:
        if x[k] <= b and not (x[k] <= a):
            ct = ct + 1
        k = k - 1
    return ct

    x = (11,10,10,5,10,15,20,10,7,11)
    y = [10000000000000000000]
    m = 0 

    while m < 10000000000000000000:  
      y[m] = m   
      m = m +1

    print(foo(x,8,18,3,6)) 
    print(foo(x,10,20,0,9))
    print(foo(x,8,18,6,3))
    print(foo(x,20,10,0,9)) 
    print(foo(x,6,7,8,8))
    # Please be careful with typos for the output of the following lines!
    print(foo(y,
         111112222233333, # five 1's, then five 2's, then five 3's
         999998888877777, # five 9's, then five 8's, then five 7's
         222223333344444, # five 2's, then five 3's, then five 4's
         905003340009900023))
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call
last) <ipython-input-17-d3d2cd54b367> in <module>()
     14 
     15 while m <  10000000000000000000:
---> 16   y[m] = m
     17   m = m +1
     18

TypeError: 'int' object does not support item assignment

【问题讨论】:

  • 你的标题和提供的内容不匹配
  • 欢迎来到 Stack Overflow!请解释一下这段代码应该做什么——这会让你更容易理解你出错的地方。

标签: python arrays arraylist


【解决方案1】:

在 python 中,当您编写 y = [10000000000000000000] 时,您正在创建一个包含索引 0 中的单个项目的数组,该数组具有 10000000000000000000 作为值。而且,也许您的想法是定义一个包含10000000000000000000 项的数组?

如果是这种情况,您要做的是:y = [] 来初始化一个数组/列表。在 python 中,你不需要指定数组的大小,它们是动态的。但是您需要使用方法来删除或添加新项目。不过,您可以使用索引更改现有项目。

如果你解决了这个问题,你仍然会在 Traceback 中得到一个箭头指向的异常,因为你试图修改一个不存在的索引的值。由于您将数组实例化为y = [10000000000000000000],因此您在索引0 中只有一个值。它第一次工作,因为循环从索引0 开始,当它设置y[0] = 0 时。但是当m 递增并尝试y[1] = 1 时,数组没有该索引,这将引发IndexError: list assignment index out of range

如果你想初始化一个包含10000000000000000000 项的数组,你可以这样做:

y = []
for i in range(10000000000000000000):
    y.append(i)

y = [i for i in range(10000000000000000000)]

更多关于range()功能:https://docs.python.org/3/library/functions.html#func-range

更多关于数组/列表:https://docs.python.org/3/tutorial/datastructures.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 2014-02-18
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多