本文介绍了使用列表推导删除列表中的元素-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表:
['A','B','C']
我需要根据我在函数中输入的内容删除一个元素.例如,如果我决定删除A,它应该返回:
What I need is to remove one element based on the input I got in the function. For example, if I decide to remove A it should return:
['B','C']
我尝试没有成功
list = ['A','B','C']
[var for var in list if list[var] != 'A']
我该怎么办?谢谢
推荐答案
简单的lst.remove('A')
可以工作:
>>> lst = ['A','B','C']
>>> lst.remove('A')
['B', 'C']
但是,对.remove
的一次调用只会删除列表中'A'
的 first 出现.要删除所有'A'
值,可以使用循环:
However, one call to .remove
only removes the first occurrence of 'A'
in a list. To remove all 'A'
values you can use a loop:
for x in range(lst.count('A')):
lst.remove('A')
如果您坚持使用列表理解,则可以使用
If you insist on using list comprehension you can use
>>> [x for x in lst if x != 'A']
['B', 'C']
以上内容将删除等于'A'
的所有所有元素.
The above will remove all elements equal to 'A'
.
这篇关于使用列表推导删除列表中的元素-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!