Tôi đăng lại câu trả lời của mình từ đây vì tôi thấy nó cũng phù hợp ở đây. Nó cho phép loại bỏ nhiều giá trị hoặc chỉ loại bỏ các bản sao của các giá trị này và trả về một danh sách mới hoặc sửa đổi danh sách đã cho tại chỗ.
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
Phần mở rộng chuỗi tài liệu:
"""
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']
"""
Bạn nên nói rõ những gì bạn thực sự muốn làm, sửa đổi danh sách hiện có hoặc tạo danh sách mới với các mục cụ thể bị thiếu. Điều quan trọng là phải tạo ra sự khác biệt đó trong trường hợp bạn có tham chiếu thứ hai trỏ đến danh sách hiện có. Ví dụ, nếu bạn có ...
li1 = [1, 2, 3, 4, 4, 5, 5]
li2 = li1
# then rebind li1 to the new list without the value 4
li1 = removed(4, li1)
# you end up with two separate lists where li2 is still pointing to the
# original
li2
# [1, 2, 3, 4, 4, 5, 5]
li1
# [1, 2, 3, 5, 5]
Đây có thể là hành vi bạn muốn.
delxóa một mục theo chỉ mục của nó. Cácremovechức năng của một danh sách tìm thấy chỉ số của một mục và sau đó gọidelvào số đó.