[英]Python- How To Remove Elements From a List Containing a Specific Word
I want to remove elements from a list containing a keyword.我想从包含关键字的列表中删除元素。
For example-例如-
list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']
I want to remove all elements in this list that contain "-test".我想删除此列表中包含“-test”的所有元素。
So the final output should be -->所以最终的 output 应该是 -->
list1= ["one", "two", "three"] #because if it contained '-test' we just deleted the element as a whole
Using list comprehension we can easily accomplish this goal.使用列表推导,我们可以轻松实现这一目标。 Also using
in
we can check if a key word is in any elements in the given list.同样使用
in
我们可以检查关键字是否在给定列表中的任何元素中。
list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']
newList = [elements for elements in list1 if '-test' not in elements]
output output
['one', 'two', 'three']
Use list comprehension
and check if the element of the list contains -test
during iteration.使用
list comprehension
并检查列表的元素是否在迭代期间包含-test
。
remove = '-test'
list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']
[x for x in list1 if remove not in x]
#['one', 'two', 'three']
The easiest way to get this done is完成这项工作的最简单方法是
list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']
for l in list1:
if '-test' in l:
list1.remove(l)
list1
Can also be done through list comprehenstion也可以通过列表理解来完成
res = []
for item in list1:
if len(item.split("-")) <=1:
res.append(item)
# res = ['one','two','three']
You can use a new array and split the given array.您可以使用新数组并拆分给定数组。 Append the values that satisfy the condition.
Append 满足条件的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.