ฉันกำลังโพสต์คำตอบของฉันใหม่จากที่นี่เพราะฉันเห็นว่ามันเหมาะกับที่นี่ อนุญาตให้ลบค่าหลายค่าหรือลบเฉพาะค่าที่ซ้ำกันของค่าเหล่านี้และส่งคืนรายการใหม่หรือแก้ไขรายการที่กำหนดแทน
def removed(items, original_list, only_duplicates=False, inplace=False):
"""By default removes given items from original_list and returns
a new list. Optionally only removes duplicates of `items` or modifies
given list in place.
"""
if not hasattr(items, '__iter__') or isinstance(items, str):
items = [items]
if only_duplicates:
result = []
for item in original_list:
if item not in items or item not in result:
result.append(item)
else:
result = [item for item in original_list if item not in items]
if inplace:
original_list[:] = result
else:
return result
ส่วนขยาย Docstring:
"""
Examples:
---------
>>>li1 = [1, 2, 3, 4, 4, 5, 5]
>>>removed(4, li1)
[1, 2, 3, 5, 5]
>>>removed((4,5), li1)
[1, 2, 3]
>>>removed((4,5), li1, only_duplicates=True)
[1, 2, 3, 4, 5]
# remove all duplicates by passing original_list also to `items`.:
>>>removed(li1, li1, only_duplicates=True)
[1, 2, 3, 4, 5]
# inplace:
>>>removed((4,5), li1, only_duplicates=True, inplace=True)
>>>li1
[1, 2, 3, 4, 5]
>>>li2 =['abc', 'def', 'def', 'ghi', 'ghi']
>>>removed(('def', 'ghi'), li2, only_duplicates=True, inplace=True)
>>>li2
['abc', 'def', 'ghi']
"""
คุณควรมีความชัดเจนเกี่ยวกับสิ่งที่คุณต้องการทำแก้ไขรายการที่มีอยู่หรือสร้างรายการใหม่โดยมีบางรายการขาดหายไป สิ่งสำคัญคือต้องสร้างความแตกต่างนั้นในกรณีที่คุณมีข้อมูลอ้างอิงที่สองที่ชี้ไปยังรายการที่มีอยู่ ถ้าคุณมีเช่น ...
li1 = [1, 2, 3, 4, 4, 5, 5]
li2 = li1
li1 = removed(4, li1)
li2
li1
นี่อาจเป็นพฤติกรรมที่คุณต้องการหรือไม่ก็ได้
delลบรายการตามดัชนีremoveฟังก์ชั่นของรายการพบว่าดัชนีของรายการและเรียกdelในดัชนีที่