sourcecode

파이썬을 사용하여 어레이에서 특정 요소를 제거하는 방법

codebag 2023. 7. 17. 20:58
반응형

파이썬을 사용하여 어레이에서 특정 요소를 제거하는 방법

배열에서 특정 요소를 제거하는 것을 쓰고 싶습니다.나는 내가 해야 한다는 것을 압니다.for배열을 반복하여 내용과 일치하는 요소를 찾습니다.

예를 들어, 전자 메일 배열이 있는데 전자 메일 문자열과 일치하는 요소를 제거하려고 합니다.

다른 배열에도 동일한 인덱스를 사용해야 하기 때문에 for 루프 구조를 실제로 사용하고 싶습니다.

제가 가지고 있는 코드는 다음과 같습니다.

for index, item in emails:
    if emails[index] == 'something@something.com':
         emails.pop(index)
         otherarray.pop(index)

배열을 반복할 필요가 없습니다.정당:

>>> x = ['ala@ala.com', 'bala@bala.com']
>>> x
['ala@ala.com', 'bala@bala.com']
>>> x.remove('ala@ala.com')
>>> x
['bala@bala.com']

문자열과 일치하는 첫 번째 항목이 제거됩니다.

편집: 편집 후에도 반복할 필요가 없습니다.그냥 하기:

index = initial_list.index(item1)
del initial_list[index]
del other_list[index]

사용.filter()그리고.lambda는 원하지 않는 값을 제거하는 깔끔하고 간결한 방법을 제공합니다.

newEmails = list(filter(lambda x : x != 'something@something.com', emails))

전자 메일은 수정되지 않습니다.익명 함수가 True를 반환한 요소만 포함하는 새 목록 새 전자 메일을 만듭니다.

for 루프가 올바르지 않습니다. 루프 사용을 위해 인덱스가 필요한 경우:

for index, item in enumerate(emails):
    # whatever (but you can't remove element while iterating)

이 경우 Bogdan 솔루션은 문제가 없지만 데이터 구조 선택은 그다지 좋지 않습니다.이 두 목록을 한 목록의 데이터와 관련된 다른 목록의 데이터를 동일한 인덱스로 유지해야 하는 것은 어렵습니다.

튜플 목록(전자 메일, 기타 데이터)이 더 나을 수도 있고 전자 메일을 키로 사용하여 받아쓰기할 수도 있습니다.

이를 위한 가장 현명한 방법을 사용하는 것입니다.zip()및 목록 이해/제너레이터 식:

filtered = (
    (email, other) 
        for email, other in zip(emails, other_list) 
            if email == 'something@something.com')

new_emails, new_other_list = zip(*filtered)

또한 사용하지 않을 경우array.array()또는numpy.array()사용하고 있을 가능성이 높습니다.[]또는list()배열이 아닌 목록을 제공합니다.같은 것이 아닙니다.

중복된 일치 항목도 처리하는 이 문제에 대한 대안이 있습니다.

길이가 같은 두 개의 목록으로 시작합니다.emails,otherarray목표는 각 인덱스의 두 목록에서 항목을 제거하는 것입니다.i어디에emails[i] == 'something@something.com'.

이것은 목록 이해를 사용하여 달성할 수 있고 다음을 통해 분할할 수 있습니다.zip:

emails = ['abc@def.com', 'something@something.com', 'ghi@jkl.com']
otherarray = ['some', 'other', 'details']

from operator import itemgetter

res = [(i, j) for i, j in zip(emails, otherarray) if i!= 'something@something.com']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))

print(emails)      # ['abc@def.com', 'ghi@jkl.com']
print(otherarray)  # ['some', 'details']

배열 인덱스를 삭제하려는 경우:

array_name.pop 사용(index_no.)

ex:-

>>> arr = [1,2,3,4]
>>> arr.pop(2)
>>>arr
[1,2,4]

배열에서 특정 문자열/요소를 삭제하려면

>>> arr1 = ['python3.6' , 'python2' ,'python3']
>>> arr1.remove('python2')
>>> arr1
['python3.6','python3']

numpy에서 setdiff1d()를 사용하여 배열에서 원하는 항목을 제거합니다.지정된 배열에서 제거할 요소 배열을 전달할 수 있습니다.

import numpy as np
test=np.array([1,2,3,4,5,45,65,34])
elements_to_remove=np.array([2,65])
t=np.setdiff1d(test,elements_to_remove)
print(test)
print(t)

출력은 다음과 같습니다.

[ 1  2  3  4  5 45 65 34]
[ 1  3  4  5 34 45]

2와 65는 원래 배열에서 제거되었습니다.

언급URL : https://stackoverflow.com/questions/7118276/how-to-remove-specific-element-from-an-array-using-python

반응형