【问题标题】:Inserting list into list containing multiple list将列表插入包含多个列表的列表中
【发布时间】:2014-04-13 13:30:04
【问题描述】:

为了知识目的

Input:

    [[[[[], [], []]], ['trynda'], [[[], [], []]]], ['cait'], [[[[], [], []]], ['veigar'], [[[], [], []]]]]

Output:

    [[[[[], [x], []]], ['trynda'], [[[], [], []]]], ['cait'], [[[[], [], []]], ['veigar'], [[[], [], []]]]]

如何将 x 添加到列表列表的第二个列表中?

【问题讨论】:

    标签: python list add


    【解决方案1】:

    只需使用嵌套索引(适用于嵌套列表):

    original_list[0][0][0][1].append(x)  # 2nd of 1st of 1st of 1st.
    

    假设x 是一个变量。否则,使用字符串,即'x'

    演示:

    >>> original_list = [[[[[], [], []]], ['trynda'], [[[], [], []]]], ['cait'], [[[[], [], []]], ['veigar'], [[[], [], []]]]]
    >>> original_list[0][0][0][1].append('x')
    >>> original_list
    [[[[[], ['x'], []]], ['trynda'], [[[], [], []]]], ['cait'], [[[[], [], []]], ['veigar'], [[[], [], []]]]]
              ^
    

    【讨论】:

      【解决方案2】:
      my_list[0][0][0][1].append(x)
      

      假设x 包含一个值。如果'x' 是一个字符串,你会想要它。

      【讨论】:

      • 永远不要使用'list'作为变量名,因为它是python的保留名。
      • @thefourtheye 这不是内置函数,它是类型,如果你想完全精确 =)
      • 既是类型又是内置函数。在我选择错误的变量名的情况下,我会覆盖内置函数docs.python.org/2/library/functions.html#list
      猜你喜欢
      • 1970-01-01
      • 2020-07-02
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      相关资源
      最近更新 更多