Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Append List เข้า List อื่น (Concatenate Lists) ใน Python

ทำได้หลายวิธี:

1. Concatenation Operator (+)

l1=[1,2,3]
l2=[2,3,4]
l3=l1+l2
print('new list', l3)
# new list [1, 2, 3, 2, 3, 4]

2. Append Method

l1=[1,2,3]
l2=[3,4,5]
l1.append(l2)
print('appended list', l1)
# appended list [3, 4, 5, [2, 3, 4]]  # l2 กลายเป็น nested list

3. Extend Method

l1=[1,2,3]
l2=[3,4,5]
l1.extend(l2)
print('extended list', l1)
# extended list [1, 2, 3, 3, 4, 5]  # flatten รวมเข้าไป

4. รวมแล้วลบ Duplicate (Unique)

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]