英文:
Why is the list value not reflected when I change the value by slicing the 2D list?
问题
我创建了一个 2D 列表 并通过对列表进行切片更改了列表的值。
mylist=[[1,3,5],[3,5,7],[5,7,9]]
mylist[1:2]=[300,400]
mylist
我期望mylist
返回 [[1,3,5],[300,400],[5,7,9]]
,但它返回了 [[1,3,5],300,400,[5,7,9]]
。
有人能解释一下吗?
谢谢。
英文:
I created 2D list and changed the value of the list by slicing the list.
mylist=[[1,3,5],[3,5,7],[5,7,9]]
mylist[1:2]=[300,400]
mylist
I expected mylist to return [[1,3,5],[300,400],[5,7,9]]
, but it returned [[1,3,5],300,400,[5,7,9]]
.
Can anyone explain this?
Thanks.
答案1
得分: 1
你需要额外的 []
要达到你想要的效果,请执行以下操作:
mylist = [[1, 3, 5], [3, 5, 7], [5, 7, 9]]
mylist[1:2] = [[300, 400]]
mylist
print(mylist)
原因:
要将单个值放入数组的单个位置,请执行以下操作:
mylist = [[1, 3, 5], [3, 5, 7], [5, 7, 9]]
mylist[1] = 300
mylist
print(mylist)
要将列表放入数组的 单个位置,请执行以下操作:
mylist = [[1, 3, 5], [3, 5, 7], [5, 7, 9]]
mylist[1] = [300, 400]
mylist
print(mylist)
你之前是在告诉它将一系列项目放入一个 位置列表
这段代码描述了一个包含一个位置(即 [1])的 位置列表。
mylist = [[1, 3, 5], [3, 5, 7], [5, 7, 9]]
###########
mylist[1:2] = [300, 400]
###########
mylist
print(mylist)
当你告诉 Python 用一个值列表替换一个位置列表时,它会执行应有的操作:删除 x 个位置并插入 y 个位置,也就是说如果 x != y,则更改列表的长度。
你需要告诉它用 长度为一的位置列表 替换 位置列表。
因此,你需要右边是一个长度为一的列表:
#############
mylist[1:2] = [ [300, 400] ]
#############
英文:
You needed an extra pair of []
Do this to get what you wanted:
mylist=[[1,3,5],[3,5,7],[5,7,9]]
mylist[1:2]=[[300,400]]
mylist
print(mylist)
Reasons:
To put a single value into a single position in an array, do this:
mylist=[[1,3,5],[3,5,7],[5,7,9]]
mylist[1]=300
mylist
print(mylist)
To put a list into a single position in an array, do this:
mylist=[[1,3,5],[3,5,7],[5,7,9]]
mylist[1]=[300,400]
mylist
print(mylist)
You were telling it to put a list of items into a list of positions
This piece of code highlighted describes a list of positions, albeit containing only one position, namely [1].
mylist=[[1,3,5],[3,5,7],[5,7,9]]
###########
mylist[1:2]=[300,400]
###########
mylist
print(mylist)
Python was doing what it should when you tell it to replace a list of x positions with a list of y values: delete x positions and insert y positions, i.e. change the length of the list if x != y.
What you need to do was to tell it to replace a list of positions with a list of length one (that happened to contain a list of two values).
Thus you needed the right hand side to be a list of length one:
#############
mylist[1:2]=[ [300,400] ]
#############
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论