.insert的python第一个参数不能是“str”

nzkunb0c  于 2023-03-04  发布在  Python
关注(0)|答案(1)|浏览(381)

这是我自己编出来的一个挑战,真的很烦人。非常感谢你的帮助。我在第5行看到一个错误,说“'str'对象不能被解释为整数”,但是它检查并验证了列表顶部的项是int,这是不必要的,但是我想也许我错了。

d = list(range(88))
print (type(d[4]))
for i in d:
    if i % 8 == 0:
        d.insert(d[i], "XOX")
    
print(d)
jobtbby3

jobtbby31#

为了让你明白,看下面的代码:

d = list(range(88))
print("d is:\n", d)
for i in d:
    print("i is :", i)
    if i % 8 == 0:
        d.insert(d[i], "XOX")
    print("Now d is: ", d)

输出:

d is:
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87]
i is : 0
Now d is:  ['XOX', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87]
i is : 0

'XOX'被插入到0th位置时,由于0向右移动,i值再次为0。现在,d[0]变为'XOX',这就是为什么会出现错误。

相关问题