[英]How to filter out list elements based on if they contain a substring from another list in Python
I have a list of strings like so called 'main_list':我有一个字符串列表,例如所谓的“main_list”:
['Hello_Kitty [data]', 'abc_xyz [data]']
and another list called 'ids'和另一个名为“ids”的列表
[abc, xyz]
I create this list by looking through 'contents_list' and appending to main_list if 'data' is found in the row entry (contents_list) is just a list of strings.如果在行条目 (contents_list) 中找到“数据”只是一个字符串列表,我通过查看“contents_list”并附加到 main_list 来创建此列表。
for entry in contents_list:
if 'data' in entry:
main_list.append(entry)
How can I filter out entries to not append anything to main_list if it contains an id from 'ids' in the substring?如果它包含来自 substring 中的“ids”的 id,我如何过滤掉不是 append 的任何内容到 main_list 的条目?
I want to end up with this:我想结束这个:
['Hello_Kitty [data]']
main_list = ['Hello_Kitty [data]', 'abc_xyz [data]']
ids = ['abc', 'xyz']
filtered_output=[]
for item in main_list:
blocked=False
for id in ids:
if id in item:
blocked=True
if blocked == False:
filtered_output.append(item)
Output:
Output:
['Hello_Kitty [data]']
You'll need to check for every id whether it is in the string before appending.在追加之前,您需要检查每个 id 是否在字符串中。 My preferred method is to use a list comprehension.
我首选的方法是使用列表推导。
I'll use the list comprehension to make a list which contains all the ids a string contains.我将使用列表推导创建一个包含字符串包含的所有 id 的列表。 If this list's length is more than 0, then that string is not appended.
如果此列表的长度大于 0,则不附加该字符串。
[id for id in ids if id in entry]
will be the list comprehension. [id for id in ids if id in entry]
将是列表理解。 This will, for each element of ids, check if that element is a substring of the entry.对于 id 的每个元素,这将检查该元素是否是条目的 substring。 If yes, that id goes into the list comprehension.
如果是,则该 id 进入列表理解。
I'll use the condition len( [id for id in ids if id in entry] ) == 0
with another if to get the job done.我将使用条件
len( [id for id in ids if id in entry] ) == 0
和另一个 if 来完成工作。 If the length is 0, no id is a substring of entry.如果长度为 0,则没有 id 是 substring 的条目。
for entry in contents_list:
if 'data' in entry:
if len( [id for id in ids if id in entry] ) == 0:
main_list.append(entry)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.