在Python中remove()将删除列表中第一个出现的值。
如何从列表中删除一个值的所有出现?
这就是我的想法:
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
在Python中remove()将删除列表中第一个出现的值。
如何从列表中删除一个值的所有出现?
这就是我的想法:
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
当前回答
有什么问题:
Motor=['1','2','2']
for i in Motor:
if i != '2':
print(i)
print(motor)
其他回答
关于速度!
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
更好的解决方案与列表理解
x = [ i for i in x if i!=2 ]
Numpy方法和对包含1.000.000个元素的列表/数组的计时:
计时:
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倍
PS如果你想将常规的Python列表lst转换为numpy数组:
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
如果你的列表只包含一个元素的副本,例如list_a=[0,0,0,0,0,0,1,3,4,6,7],下面的代码将是有帮助的:
list_a=[0,0,0,0,0,0,1,3,4,6,7]
def remove_element(element,the_list):
the_list=list(set(the_list))
the_list.remove(element)
return the_list
list_a=remove_element(element=0,the_list=list_a)
print(list_a)
or
a=list(set(i for i in list_a if i!=2))
a.remove(2)
基本思想是集合不允许重复,因此首先我将列表转换为set(删除重复项),然后使用.remove()函数删除元素的第一个实例(因为现在每个项只有一个实例)。
但如果你有多个元素的副本,下面的方法会有帮助:
列表理解
list_a=[1, 2, 3, 4, 2, 2, 3]
remove_element=lambda element,the_list:[i for i in the_list if i!=element]
print(remove_element(element=2,the_list=list_a))
过滤器
list_a=[1, 2, 3, 4, 2, 2, 3]
a=list(filter(lambda a: a != 2, list_a))
print(a)
While循环
list_a=[1, 2, 3, 4, 2, 2, 3]
def remove_element(element,the_list):
while element in the_list:the_list.remove(element)
return the_list
print(remove_element(2,list_a))
for循环(与列表推导式相同)
list_a=[1, 2, 3, 4, 2, 2, 3]
a=[]
for i in list_a:
if i!=2:
a.append(i)
print(a)
有什么问题:
Motor=['1','2','2']
for i in Motor:
if i != '2':
print(i)
print(motor)