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

วิธีลบสมาชิกซ้ำในลิสต์ด้วย Python

ย้าย return statement นอกบล็อก for จะทำงานได้ นอกจากนี้ print ตัวสุดท้ายควรเป็น remove_same ไม่ใช่ remaove_new

def remove_same(L1, L2):
    L1_copy = L1[:]
    for e in L1_copy:
        if e in L2:
            L1.remove(e)
    return L1

L1 = [1,2,3,4]
L2 = [1,2,5,6]
print(remove_same(L1, L2))

ผลลัพธ์:

[3, 4]