Programming

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

procodes 2020. 7. 27. 08:03
반응형

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


배열에서 특정 요소를 제거하는 것을 작성하고 싶습니다. 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를 리턴 한 요소 만 포함하는 newEmails 새 목록을 작성합니다.


이 작업을 수행하는 올바른 방법은 다음 zip()과 같은 목록 이해 / 생성기 표현을 사용하는 것입니다.

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

new_emails, new_other_list = zip(*filtered)

또한, your'e는 사용하지 않을 경우 array.array()또는 numpy.array()다음, 가장 가능성이 당신이 사용하고 []또는 list()당신에게하지 배열 목록을 제공한다. 같은 것이 아닙니다.


for 루프에서 색인이 필요한 경우 for 루프가 올바르지 않습니다.

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

귀하의 경우 Bogdan 솔루션은 괜찮지 만 데이터 구조 선택은 그리 좋지 않습니다. 같은 인덱스에있는 다른 데이터와 관련된 데이터를 사용하여이 두 목록을 유지 관리하는 것은 어색합니다.

Tupple (이메일, 기타 데이터) 목록이 더 좋거나 이메일을 키로 사용하는 것이 좋습니다.


이 문제에 대한 대체 솔루션이 중복 일치를 처리합니다.

동일한 길이의 두 목록으로 시작합니다 : 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']

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

반응형