Python错误集锦:list切片赋值时提示ValueError: attempt to assign sequence of size 3 to extended slice of size 4

原文链接:http://www.juzicode.com/python-error-assign-sequence-extended-slice-wrong-size

错误提示:

list切片赋值时提示ValueError: attempt to assign sequence of size 3 to extended slice of size 4

#juzicode.com/vx:桔子code
lst = [0,1,2,3,4,5,6,7,8,9]
lst[2::2] = [22,23,24]
print("lst =",lst)
==========运行结果:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-5c459935585a> in <module>
      1 #juzicode.com/vx:桔子code
      2 lst = [0,1,2,3,4,5,6,7,8,9]
----> 3 lst[2::2] = [22,23,24]
      4 print("lst =",lst)

ValueError: attempt to assign sequence of size 3 to extended slice of size 4

错误原因:

1、lst长度为10,lst[2::2] = [22,23,24]表示要对从下标2开始步长为2的元素重新赋值,lst[2::2]包含了下标2,4,6,8的4个元素,但是被赋值的对象为[22,23,24]只有3个元素,所以提示赋值的序列长度不对。

解决方法:

1、如果原意是要修改下标为2,4,6的3个元素,可以将结束下标限定在7或8,写成lst[2:7:2] = [22,23,24]或lst[2:8:2] = [22,23,24]

#juzicode.com/vx:桔子code
lst = [0,1,2,3,4,5,6,7,8,9]
lst[2:8:2] = [22,23,24]
print("lst =",lst)
==========运行结果:
lst = [0, 1, 22, 3, 23, 5, 24, 7, 8, 9]

2、如果原意是要修改下标为2以后的元素为[22,23,24],可以改为lst[2:] = [22,23,24]:

#juzicode.com/vx:桔子code
lst = [0,1,2,3,4,5,6,7,8,9]
lst[2:] = [22,23,24]
print("lst =",lst)
==========运行结果:
lst = [0, 1, 22, 23, 24]

扩展内容:

  1. Python基础教程2c–数据类型-list(列表)
  2. Python列表的索引切片还可以这么理解


如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注