简体   繁体   English

如果 List 中的元素包含一个单词 | Python

[英]if Element in List contains a word | Python

Say I have a list:假设我有一个清单:

my_list = ["A", "B", "haha_test_haha", "C"]

I want to remove any and all elements that hold the substring test .我想删除所有持有 substring test的元素。

Output: Output:

my_list = ["A", "B", "C"]

I've been trying list comprehensions with no luck.我一直在尝试列表推导,但没有运气。 This would be the desired solution.这将是理想的解决方案。

Note: I need only test to be removed.注意:我只需要删除test即可。 Not a list of words to remove.不是要删除的单词列表。


My attempt:我的尝试:

my_list = ['A', 'B', 'C', 'C', 'ahahtestaagaga']

my_list = [remove for e in my_list if e.substring('test')]

print([sa for sa in a if not any(sb in sa for sb in b)])
my_list = [word for word in my_list if 'test' not in word]

Think about what it would look like as a for loop, so for the sake of the example, let's build a new list (even though it's inefficient), you want to capture things that don't have "test" as a substring:想想它看起来像一个 for 循环,所以为了这个例子,让我们构建一个新列表(即使它效率低下),你想要捕获没有“测试”的东西作为 substring:

new_list = []
for x in my_list:
    if "test" not in x:
        new_list.append(x)

So what would that look like as a comprehension?那么这会是什么样的理解呢?

my_list = [x for x in my_list if "test" not in x]

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

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