[英]how to use the slice operator to change element in nested list
testlist = [1, 4, 9, 'sixteen', ['25', '...']]
我想使用切片运算符将嵌套列表的最后一个元素更改为36.我该怎么做?
You can do it as follows: 你可以这样做:
>>> testlist = [1 , 4 , 9 , 'sixteen ', ['25 ', '... ']]
>>> testlist[-1][-1] = '36'
[1, 4, 9, 'sixteen', ['25', '...', '36']]
If you simply want to add on as the last element instead of replace, do: testlist[-1].append('36')
instead 如果您只想添加为最后一个元素而不是替换,请执行: testlist[-1].append('36')
In lists, the -1
index gets the last element of a list. 在列表中, -1
索引获取列表的最后一个元素。 However, if your nested list is not always last, you can do: 但是,如果嵌套列表并不总是最后一个,则可以执行以下操作:
>>> testlist[i][-1] = '36
where i
is the position of the nested list in testlist
. 其中i
是testlist
嵌套列表的testlist
。 More generally, you can do: 更一般地说,你可以这样做:
>>> testlist[i][j] = '36'
where i
fetches the ith
element in testlist
and j
fetches the jth
element in the ith
element. 其中i
在testlist
获取第ith
元素, j
获取jth
ith
jth
元素中的ith
jth
ith
元素。
>>> a = [[1,2],[3,4],[5,6]] #note the nested lists
>>> a[1][1]
4
>>> a[-1][-1]
6
>>> a[-1][0]
5
>>> a[0][-1]
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.