목록에서 모든 값을 제거 하시겠습니까?
파이썬에서는 remove()목록에서 처음 나타나는 값을 제거합니다.
목록에서 모든 값 을 제거하는 방법은 무엇입니까?
이것이 내가 생각한 것입니다.
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
기능적 접근 방식 :
2.x
>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]
3.x
>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]
또는
>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]
목록 이해를 사용할 수 있습니다.
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
print x
# [1, 3, 4, 3]
효율적인 목록 이해 (또는 생성기 표현식)를 사용하면서 원래 목록을 수정해야하는 경우 슬라이스 할당을 사용할 수 있습니다.
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> x[:] = (value for value in x if value != 2)
>>> x
[1, 3, 4, 3]
보다 추상적 인 방식으로 첫 번째 게시물의 솔루션을 반복합니다.
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> while 2 in x: x.remove(2)
>>> x
[1, 3, 4, 3]
간단한 솔루션보기
솔루션 1 :
>>> [i for i in x if i != 2]
솔루션 2 가 x없는 모든 요소가있는 목록이 반환됩니다 2
.
>>> while 2 in x : x.remove(2)
위의 모든 답변 (Martin Andersson 's 제외)은 원래 목록에서 항목을 제거하지 않고 원하는 항목없이 새 목록을 만듭니다.
>>> import random, timeit
>>> a = list(range(5)) * 1000
>>> random.shuffle(a)
>>> b = a
>>> print(b is a)
True
>>> b = [x for x in b if x != 0]
>>> print(b is a)
False
>>> b.count(0)
0
>>> a.count(0)
1000
>>> b = a
>>> b = filter(lambda a: a != 2, x)
>>> print(b is a)
False
목록에 대한 다른 참조가 있으면 중요 할 수 있습니다.
목록을 제자리에 수정하려면 다음과 같은 방법을 사용하십시오
>>> def removeall_inplace(x, l):
... for _ in xrange(l.count(x)):
... l.remove(x)
...
>>> removeall_inplace(0, b)
>>> b is a
True
>>> a.count(0)
0
속도와 관련하여 랩톱의 결과는 모두 1000 개의 항목이 제거 된 5000 개의 항목 목록에 있습니다.
- 목록 이해-~ 400us
- 필터-~ 900us
- .remove () 루프-50ms
따라서 .remove 루프는 약 100 배 느립니다. ...... 흠, 다른 접근법이 필요할 수 있습니다. 내가 찾은 가장 빠른 것은 목록 이해를 사용하는 것이지만 원래 목록의 내용을 바꿉니다.
>>> def removeall_replace(x, l):
.... t = [y for y in l if y != x]
.... del l[:]
.... l.extend(t)
- removeall_replace ()-450us
가독성을 위해이 버전은 목록을 다시 검사 해야하는 시간을 강요하지 않기 때문에 약간 더 빠르다고 생각합니다. 따라서 정확히 제거 작업을 수행해야합니다.
x = [1, 2, 3, 4, 2, 2, 3]
def remove_values_from_list(the_list, val):
for i in range(the_list.count(val)):
the_list.remove(val)
remove_values_from_list(x, 2)
print(x)
당신은 이것을 할 수 있습니다
while 2 in x:
x.remove(2)
1.000.000 요소의 목록 / 배열에 대한 Numpy 접근 방식 및 타이밍 :
타이밍 :
In [10]: a.shape
Out[10]: (1000000,)
In [13]: len(lst)
Out[13]: 1000000
In [18]: %timeit a[a != 2]
100 loops, best of 3: 2.94 ms per loop
In [19]: %timeit [x for x in lst if x != 2]
10 loops, best of 3: 79.7 ms per loop
결론 : numpy는 목록 이해 접근법에 비해 27 배 빠릅니다 (노트북에서).
일반 파이썬 목록 lst을 numpy 배열 로 변환하려면 PS :
arr = np.array(lst)
설정:
import numpy as np
a = np.random.randint(0, 1000, 10**6)
In [10]: a.shape
Out[10]: (1000000,)
In [12]: lst = a.tolist()
In [13]: len(lst)
Out[13]: 1000000
검사:
In [14]: a[a != 2].shape
Out[14]: (998949,)
In [15]: len([x for x in lst if x != 2])
Out[15]: 998949
중복 항목을 모두 제거하고 목록에 그대로 두려면 다음을 수행하십시오.
test = [1, 1, 2, 3]
newlist = list(set(test))
print newlist
[1, 2, 3]
Project Euler에 사용한 함수는 다음과 같습니다.
def removeOccurrences(e):
return list(set(e))
a = [1, 2, 2, 3, 1]
to_remove = 1
a = [i for i in a if i != to_remove]
print(a)
아마도 가장 파이썬 적이지는 않지만 여전히 가장 쉬운 방법입니다.
목록 주문에 신경 쓰지 않으면 최종 주문 저장에주의를 기울이면 색인을 원본 및 리조트의 색인으로 저장하는 것이 다른 방법보다 빠르다고 생각합니다.
category_ids.sort()
ones_last_index = category_ids.count('1')
del category_ids[0:ones_last_index]
for i in range(a.count(' ')):
a.remove(' ')
훨씬 간단하게 믿습니다.
파이썬 목록에서 모든 값을 제거하십시오.
lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list():
for list in lists:
if(list!=7):
print(list)
remove_values_from_list()
결과: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11
또는
lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list(remove):
for list in lists:
if(list!=remove):
print(list)
remove_values_from_list(7)
결과: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11
첫 번째 해결책은 필터를 사용하는 것입니다.
목록 이해를 사용하는 두 번째 솔루션.
#If we want to remove all 2.
ls = [2, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 6, 2]
# 1-filter takes two arguments(condition,sequence)
ls = list(filter(lambda x: x != 2, ls))
# 2-list comprehension
ls = [x for x in ls if x != 2]
무엇이 잘못 되었나요?
Motor = [ '1', '2', '2'] 모터의 i의 경우 : i! = '2'인 경우 : 인쇄 (i) 인쇄 (모터)
아나콘다 사용하기
내장 filter이 없거나 여분의 공간을 사용하고 싶지 않고 선형 솔루션이 필요한 경우 ...
def remove_all(A, v):
k = 0
n = len(A)
for i in range(n):
if A[i] != v:
A[k] = A[i]
k += 1
A = A[:k]
hello = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#chech every item for a match
for item in range(len(hello)-1):
if hello[item] == ' ':
#if there is a match, rebuild the list with the list before the item + the list after the item
hello = hello[:item] + hello [item + 1:]
print hello
[ 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
허락하다
>>> x = [1, 2, 3, 4, 2, 2, 3]
이미 게시 된 가장 간단하고 효율적인 솔루션은
>>> x[:] = [v for v in x if v != 2]
>>> x
[1, 3, 4, 3]
더 적은 메모리를 사용해야하지만 느려질 수있는 다른 가능성은
>>> for i in range(len(x) - 1, -1, -1):
if x[i] == 2:
x.pop(i) # takes time ~ len(x) - i
>>> x
[1, 3, 4, 3]
10 % 일치 항목이있는 길이 1000 및 100000의 목록에 대한 타이밍 결과 : 0.16 vs 0.25 ms 및 23 vs 123 ms
방금 목록을 작성했습니다. 나는 단지 초보자입니다. 약간 더 고급 인 프로그래머라면 반드시 이와 같은 함수를 작성할 수 있습니다.
for i in range(len(spam)):
spam.remove('cat')
if 'cat' not in spam:
print('All instances of ' + 'cat ' + 'have been removed')
break
속도에 대해!
import time
s_time = time.time()
print 'start'
a = range(100000000)
del a[:]
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 3.25
s_time = time.time()
print 'start'
a = range(100000000)
a = []
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 2.11
p=[2,3,4,4,4]
p.clear()
print(p)
[]
파이썬 3에서만
참고 URL : https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list
'development' 카테고리의 다른 글
| AsyncTask가 별도의 클래스이기 때문에 OnPostExecute () 결과를 주요 활동으로 가져 오는 방법은 무엇입니까? (0) | 2020.03.04 |
|---|---|
| SQL Server Management Studio 및 Transact SQL에서 GO를 사용하는 것은 무엇입니까? (0) | 2020.03.04 |
| 요청으로 파이썬에서 큰 파일 다운로드 (0) | 2020.03.04 |
| int []를 List로 변환하는 방법 (0) | 2020.03.04 |
| Emacs에서 글꼴 크기를 설정하는 방법은 무엇입니까? (0) | 2020.03.04 |

