【问题标题】:How to append a list into a list如何将列表附加到列表中
【发布时间】:2019-05-26 12:02:14
【问题描述】:

我想附加一些会像 list1 一样输出的东西。列表中的列表,我该怎么做? 我不在乎你如何将 abc 放入列表,但我想知道如何将该列表放入 list1,以便 list1 可以成为列表中的列表。 我希望输出是这样的

x = a,b,c
list1 = []
list1 = [[a,b,c],[a,b,c]]

【问题讨论】:

  • 尝试list1 = [1, 2, 3],然后尝试list2 = [list1, list1]。这将为list2 提供[[1, 2, 3], [1, 2, 3]]
  • 您也可以使用list2.append(list1)list1 附加到list2
  • 使用list1.append(list2)

标签: python list


【解决方案1】:

函数“append”用于将对象添加到列表的末尾。由于列表是一个对象,如果您将另一个列表附加到列表上,则第一个列表将是列表末尾的单个对象。

my_list = ['a', 'b', 'c'] 
another_list = [1, 2, 3] 
my_list.append(another_list) 
print(my_list) 
= "['a', 'b', 'c', [1, 2, 3]]" 

使用以下语法可以得到相同的结果:

my_list = ['a', 'b', 'c'] 
new_list = [my_list, my_list, my_list] 
print(new_list) 
= "[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]" 

函数“extend”迭代其参数,将每个元素添加到列表并扩展列表。列表的长度随着添加的元素数量的增加而增加。

my_list = ['a', 'b', 'c'] 
another_list = [1, 2, 3] 
my_list.extend(another_list) 
print(my_list) 
= "['a', 'b', 'c', 1, 2, 3]

使用列表之间的简单求和可以获得与扩展相同的结果:

my_list = ['a', 'b', 'c'] 
another_list = [1, 2, 3] 
print(my_list + another_list) 
= "['a', 'b', 'c', 1, 2, 3]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多