하나의 문장에서 여러 항목을 목록에서 제거하려면 어떻게 해야 합니까?
python에서는 목록에서 항목을 삭제하는 방법을 알고 있습니다.
item_list = ['item', 5, 'foo', 3.14, True]
item_list.remove('item')
item_list.remove(5)
는 값 을 '5'에서 삭제합니다.item_list하지만 제거할 것이 많을 때는 다음과 같이 여러 줄을 작성해야 합니다.
item_list.remove("something_to_remove")
삭제할 인덱스를 알고 있는 경우 다음을 사용합니다.
del item_list[x]
여기서 x는 삭제할 항목의 인덱스입니다.
「」에의 합니다.del지수의 항목
그러나 삭제할 항목의 인덱스를 모를 경우 어떻게 해야 합니까?
는 는 i i는노노 i i i i i.item_list.remove('item', 'foo') ''가 나왔어요remove1번으로 하다
하나의 문장으로 목록에서 여러 항목을 삭제할 수 있는 방법이 있습니까?
는 ,, 는을 del ★★★★★★★★★★★★★★★★★」remove이 둘의 차이점을 설명해 줄 수 있는 사람이 있나요? 니면면 같은 ?? ????
Python에서는 목록 이해 기능을 사용하여 새 개체를 만드는 것이 기존 개체를 수정하는 것보다 더 나은 경우가 많습니다.
item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]
...이것은, 다음과 같습니다.
item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
if e not in ('item', 5):
new_list.append(e)
item_list = new_list
값의(여기서 「」는 「」로 합니다).('item', 5)작은 요소 세트)를 사용하여 a를 사용하는 것이 고속입니다.in동작은 평균 O(1)시간 복잡도입니다.목록 이해의 모든 반복에서 반복을 만들지 않도록 먼저 제거할 반복을 작성하는 것도 좋습니다.
unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]
목록을 로 변환하고 를 사용하여 한 줄로 표시할 수 있습니다.
item_list = ['item', 5, 'foo', 3.14, True]
list_to_remove = ['item', 5, 'foo']
final_list = list(set(item_list) - set(list_to_remove))
다음과 같은 출력을 얻을 수 있습니다.
final_list = [3.14, True]
주의: 입력 목록에서 중복된 항목이 제거되고 출력 요소가 임의의 순서로 정렬될 수 있습니다.set순서를 유지하지 않습니다).또한 두 목록의 모든 요소가 해시 가능해야 합니다.
여기에도 딱 들어맞는 걸 보고 여기서 답변을 다시 올리는 거예요.여러 값을 삭제하거나 이러한 값의 중복만 제거할 수 있으며 새 목록을 반환하거나 지정된 목록을 수정할 수 있습니다.
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]
이것은 당신이 원하는 행동일 수도 있고 아닐 수도 있다.
반복 도구 모듈에서 filterfalse 함수를 사용할 수 있습니다.
예
import random
from itertools import filterfalse
random.seed(42)
data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")
clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")
출력:
Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]
Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]
사용할 수 있습니다.
리스트가 있다고 가정해봅시다l = [1,2,3,4,5]
단일 문장에서 마지막 두 항목을 삭제하려고 합니다.
del l[3:]
출력:
l = [1,2,3]
단순하게 받아들여라.
왜 모든 사람들이 이 놀라운 능력을 언급하는 것을 잊었는지 모르겠다.sets는 python 입니다.목록을 세트로 캐스팅한 후 다음과 같이 간단한 표현식으로 삭제할 수 있습니다.
>>> item_list = ['item', 5, 'foo', 3.14, True]
>>> item_list = set(item_list) - {'item', 5}
>>> item_list
{True, 3.14, 'foo'}
>>> # you can cast it again in a list-from like so
>>> item_list = list(item_list)
>>> item_list
[True, 3.14, 'foo']
그러나 삭제할 항목의 인덱스를 모를 경우 어떻게 해야 합니까?
.remove를 좋아하지 않는 이유를 정확히 알 수 없지만 값에 대응하는 첫 번째 인덱스를 얻으려면 .index(value)를 사용합니다.
ind=item_list.index('item')
그런 다음 해당 값을 제거합니다.
del item_list[ind]
.index(value)는 값의 첫 번째 오카렌스를 가져오고 .remove(value)는 값의 첫 번째 오카렌스를 삭제합니다.천만예요.
다음과 같은 my_list가 있다고 가정합니다.중복된 0을 리스트에서 삭제하고 싶습니다.remove()를 사용하면 0을 1개만 삭제할 수 있지만 다음 코드에서는 중복된0 을 한 번에 모두 삭제할 수 있습니다.
my_list = [1, 2, 3, 0, 0, 0, 3, 4]
list(filter(lambda a: a != 0, my_list))
output:
[1, 3, 3, 4]
여러 요소를 제거할 수 있습니다.
list1=[1,2,3,4,5,200,30]
del list1 [ 1 : 3 ]
print(리스트1)
[1,4,5,200,30]
numpy 배열과 설정 함수를 결합하여 유지할 요소만 표시하는 새 배열이 되도록 할 수 있습니다.
import numpy as np
# given an array A:
A = [5,78,423,87,45,78,4]
# first convert your array to a numpy array
A_np = np.array(A)
# specify the indices you want to remove
inds_to_be_deleted = [3,5]
# find the remaining indices using set function
remaining_inds = list(set(range(len(A)))-set(inds_to_be_deleted))
# the new array will only contain the elements at the remaining indices
A_new = A_np[remaining_inds]
출력은 다음과 같습니다.array ( [ 5, 78 , 423, 45 , 4 ] )
언급URL : https://stackoverflow.com/questions/36268749/how-to-remove-multiple-items-from-a-list-in-just-one-statement
'programing' 카테고리의 다른 글
| 각 서브리스트의 첫 번째 아이템 추출 (0) | 2023.04.15 |
|---|---|
| XAML의 부울 명령어파라미터 (0) | 2023.04.15 |
| UITableView에서 빈 셀 사이의 구분 기호를 강제로 숨길 수 있습니까? (0) | 2023.04.15 |
| WPF 어플리케이션을 Windows 7에서도 메트로 스타일로 할 수 있습니까? (Windows Chrome / Theming / Theme ) (0) | 2023.04.15 |
| 데이터 프레임 목록을 작성하려면 어떻게 해야 합니까? (0) | 2023.04.10 |