나는 여기에도 맞는 것을 보았 기 때문에 여기 에서 내 대답을 다시 게시 하고 있습니다. 여러 값을 제거하거나 이러한 값의 중복 만 제거 할 수 있으며 새 목록을 반환하거나 주어진 목록을 제자리에서 수정합니다.
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
독 스트링 확장 :
"""
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
# 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]
이것은 당신이 원하는 행동 일 수도 있고 아닐 수도 있습니다.
del색인별로 항목을 삭제합니다.remove목록 의 기능은 항목의 색인을 찾은 다음del해당 색인 을 호출 합니다.