【问题标题】:how to use the slice operator to change element in nested list如何使用切片运算符更改嵌套列表中的元素
【发布时间】:2014-05-16 13:30:57
【问题描述】:
testlist = [1, 4, 9, 'sixteen', ['25', '...']]

我想使用切片运算符将嵌套列表的最后一个元素更改为 36。我该怎么做?

【问题讨论】:

  • 欢迎来到stackoverflow。如果以下答案之一解决了您的问题,您应该接受它(单击相应答案旁边的复选标记)。这有两件事。它让每个人都知道您的问题已得到解决,并为帮助您的人提供帮助。完整的解释见here
  • 我的回答有帮助吗?如果是,你介意接受吗?谢谢。

标签: python list nested slice


【解决方案1】:

你可以这样做:

>>> testlist = [1 , 4 , 9 , 'sixteen ', ['25 ', '... ']]
>>> testlist[-1][-1] = '36'
[1, 4, 9, 'sixteen', ['25', '...', '36']]

如果您只是想作为最后一个元素添加而不是替换,请改为:testlist[-1].append('36')

在列表中,-1 索引获取列表的最后一个元素。但是,如果您的嵌套列表并不总是最后,您可以这样做:

>>> testlist[i][-1] = '36

其中itestlist 中嵌套列表的位置。更一般地说,您可以这样做:

>>> testlist[i][j] = '36'

其中i 获取testlist 中的ith 元素,j 获取ith 元素中的jth 元素。

示例

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

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2013-09-11
    • 2021-01-13
    • 2021-12-03
    • 2020-11-14
    • 2011-02-13
    相关资源
    最近更新 更多