วิธีการลบรายการซ้ำจาก List ใน Python
- หน้าก่อน ของมอดูล
- หน้าต่อไป ความย้อนกลับของตัวอักษร
เรียนรู้วิธีการลบรายการซ้ำจาก List ใน Python
ตัวอย่าง
ลบรายการซ้ำจาก List
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
การชี้แจงตัวอย่าง
เบื้องต้น หากเรามี List ที่มีรายการซ้ำ
รายการที่มีรายการซ้ำ
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
สร้างแปลงรายการในตัวชี้วัดใช้ตัวเลือกใน List จะลบรายการซ้ำอัตโนมัติ เพราะฐานข้อมูลไม่อนุญาตให้มีการซ้ำในฟิลด์ตัวชี้วัด
สร้างฐานข้อมูล
mylist = ["a", "b", "a", "c", "c"] mylist = list( dict.fromkeys(mylist) ) print(mylist)
ดังนั้น แปลงแปลงรายการในตัวชี้วัดเป็น List อีกครั้ง
แปลงเป็น List
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
ขณะนี้เรามี List ที่ไม่มีการซ้ำ ซึ่งมีลำดับเดียวกับ List ต้นฉบับ
พิมพ์รายการเพื่อแสดงผลลัพธ์:
พิมพ์รายการ
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)
การอธิบายตัวอย่าง
สร้างฟังก์ชันที่มีรายการเลือกเป็นตัวอักษร
สร้างฟังก์ชัน
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 listdict.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)
- หน้าก่อน ของมอดูล
- หน้าต่อไป ความย้อนกลับของตัวอักษร