简体   繁体   English

如何删除 python 列表中的特定值

[英]How to remove Specific values in python list

result = [(u'ABC', u'(Choose field)', u'ABCD', u'aa', u'A', u'A_100')]

I'm trying to remove '(Choose field)' from the above list using the following syntax:我正在尝试使用以下语法从上面的列表中删除'(Choose field)'

result.remove('(Choose field)')
# and  
result.remove("'(Choose field)'")

But both things are not working fine and it ends up with this error但是这两件事都不能正常工作,最终会出现这个错误

{ValueError}list.remove(x): x not in list

First of all, your list contains tuple which contains string.首先,您的列表包含包含字符串的元组。 And tuple doesn't support remove Just convert tuples as list and then use remove并且元组不支持remove只需将元组转换为列表然后使用remove

>>> res = list(result[0])
['ABC', '(Choose field)', 'ABCD', 'aa', 'A', 'A_100']
>>> res.remove('(Choose field)')
['ABC', 'ABCD', 'aa', 'A', 'A_100']

You can convert the tuple inside the list to another list and remove the item from there.您可以将列表中的元组转换为另一个列表并从那里删除该项目。 This should do the work:-这应该可以完成工作:-

result = list(result[0])
result.remove(u'(Choose field)')

If you want to use indexing and specifically want to remove 'a' and 'b' from distinct list: values = ['a', 1, 2, 3, 'b'] - you can do this:如果你想使用索引,特别是想从不同的列表中删除'a''b'values = ['a', 1, 2, 3, 'b'] - 你可以这样做:

pop_list=['a','b']
[values.pop(values.index(p))  for p in pop_list if p in values]    

above will remove 'a' and 'b' in place - to get :上面将删除'a''b' -得到

print(values)   

[1, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM