如何在Python中将列表追加到第二个列表(并置列表)?
这可以通过不同的方式完成-
使用串联运算符
示例
l1=[1,2,3]
l2=[2,3,4]
l3=l1+l2
print ('new list', l3)输出结果
这将打印
new list [1, 2, 3, 2, 3, 4]
使用列表对象的append方法
示例
l1=[1,2,3]
l1=[3,4,5]
l1.append(l2)
print ('appended list', l1)输出结果
这是结果
appended list [3, 4, 5, [2, 3, 4]]
使用扩展方法
示例
l1=[1,2,3]
l1=[3,4,5]
l1.extend(l2)
print ('extended list', l1)输出结果
输出如下-
extended list [1, 2, 3, 3, 4, 5]
获取没有重复的列表
首先连接列表,然后使用set()函数消除重复项,然后使用list()函数将集合转换为列表
示例
l1=[1,2,3]
l2=[3,4,5]
l=list(set(l1+l2))
print ('list without duplicates',l)输出结果
结果列表对象将是
list without duplicates [1, 2, 3, 4, 5]