我是Python的新用户。我想从列表中提取特定值。我的例子是提取除-1之外的值。实现这一过程的智能方法是什么?
a = [-1, 0, 2,-1, 30]
# new_a = ?? # extract values except for -1
-> new_a = [0, 2, 30]
答案 0 :(得分:5)
>>> a = [-1, 0, 2,-1, 30]
>>> new_a=list(filter(lambda x:x!=-1, a))
>>> print(new_a)
[0, 2, 30]
或
>>> new_a=[i for i in a if i!=-1]
>>> print(new_a)
[0, 2, 30]
或在if
for
的旧学校方式
>>> new_a=[]
>>> for i in a:
... if i!=-1:
... new_a+=[i]
...
>>> print(new_a)
[0, 2, 30]
答案 1 :(得分:-2)
In [74]: a = [-1, 0, 2,-1, 30]
In [75]: list(set(a)-set([-1]))
Out[75]: [0, 2, 30]