วิธีลบรายการที่ซ้ำกันออกจากรายการ Python
เรียนรู้วิธีลบรายการที่ซ้ำกันออกจากรายการใน Python
ตัวอย่าง
ลบรายการที่ซ้ำกันออกจากรายการ:
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
ตัวอย่างที่อธิบาย
อันดับแรก เรามีรายการที่มีรายการที่ซ้ำกัน:
รายการที่ซ้ำกัน
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
สร้างพจนานุกรมโดยใช้รายการเป็นคีย์ การดำเนินการนี้จะลบรายการที่ซ้ำกันโดยอัตโนมัติเนื่องจากพจนานุกรมไม่สามารถมีคีย์ที่ซ้ำกันได้
สร้างพจนานุกรม
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
จากนั้นแปลงพจนานุกรมกลับเป็นรายการ:
แปลงเป็นรายการ
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
ตอนนี้ เรามีรายการที่ไม่มีรายการซ้ำ และมีลำดับเดียวกันกับรายการดั้งเดิม
พิมพ์รายการเพื่อแสดงผล
พิมพ์รายการ
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
สร้างฟังก์ชัน
หากคุณต้องการมีฟังก์ชันที่คุณสามารถส่งรายการของคุณและนำรายการกลับมาโดยไม่มีรายการซ้ำ คุณสามารถสร้างฟังก์ชันและแทรกโค้ดจากตัวอย่างด้านบนได้
ตัวอย่าง
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
ตัวอย่างที่อธิบาย
สร้างฟังก์ชันที่ใช้ List เป็นอาร์กิวเมนต์
สร้างฟังก์ชัน
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
สร้างพจนานุกรมโดยใช้รายการนี้เป็นคีย์
สร้างพจนานุกรม
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
แปลงพจนานุกรมเป็นรายการ
แปลงเป็นรายการ
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
กลับรายการ
กลับรายการ
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
เรียกใช้ฟังก์ชันโดยมีรายการเป็นพารามิเตอร์:
เรียกฟังก์ชัน
def my_function(x):
return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)
พิมพ์ผลลัพธ์:
พิมพ์ผลลัพธ์
def my_function(x):
return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)