为什么在我通过切片更改二维列表的值时,列表的值没有反映出来?

huangapple go评论64阅读模式
英文:

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] ]
            #############

huangapple
  • 本文由 发表于 2023年4月6日 23:43:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定