Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将一些字符串添加到Python中已经存在的列表中?_Python_Arrays_List - Fatal编程技术网

如何将一些字符串添加到Python中已经存在的列表中?

如何将一些字符串添加到Python中已经存在的列表中?,python,arrays,list,Python,Arrays,List,我想要的是 list1 = ['1', '2', '3', '4'] input_list = ['5', '6'] 我尝试了很多其他的方法,但都没有得到我想要的结果。。 我还搜索了其他Q&A以找到方法,但我也找不到。。 谢谢你的帮助 使用extend将列表添加到另一个列表中,使用append将元素添加到列表中 print(list1) >> ['1','2','3','4','5'] >> ['1','2','3','4','6'] 您可以通过添加两个列表来连接它们

我想要的是

list1 = ['1', '2', '3', '4']
input_list = ['5', '6']
我尝试了很多其他的方法,但都没有得到我想要的结果。。 我还搜索了其他Q&A以找到方法,但我也找不到。。
谢谢你的帮助

使用extend将列表添加到另一个列表中,使用append将元素添加到列表中

print(list1)
>> ['1','2','3','4','5']
>> ['1','2','3','4','6']

您可以通过添加两个列表来连接它们。
[1,2]+[3]
将产生
[1,2,3]
您也可以使用extend或append方法

如何

list1.extend(input_list)
list1.append('5')
list1.append('6')
结果

import copy

list1 = ['1', '2', '3', '4']
input_list = ['5', '6']

output = []
for e in input_list:
    l = copy.copy(list1)
    l.append(e)
    output.append(l)

print(output)

诀窍是
copy()
要创建一个新列表

作为@Kenji的解决方案的替代方案,您可以使用一个简单的一行代码:

[['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '6']]
完整程序:

res = [list1+[i] for i in input_list]

extend
+=
。一个是函数,另一个是复合运算符。您能更具体地解释一下吗?
list1.extend(input\u list)
。阅读@Kristine
list1.extend(input\u list)
。通过简单的谷歌搜索可以找到解决方案创建
list1
副本的更好方法不是简单地说
list1[:]
list1 = ['1', '2', '3', '4']
input_list = ['5', '6']

res = [list1+[i] for i in input_list]
print(res) # prints: [['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '6']]