检查Python列表项是否在另一个lis的另一个字符串中包含一个字符串

2024-06-16 11:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名单,其中包括如下国家:

country = ["england","france","germany"]

我想使用此列表并检查这些值是否在其他字符串列表中,例如:

urllist = ["http://uk.soccerway.com/matches/2017/02/22/germany/oberliga/tus-mechtersheim-1914/hertha-wiesbach/2300594/head2head/","http://uk.soccerway.com/matches/2017/02/22/india/u18-league/delhi-united-sc-u18/sudeva-u18/2397728/head2head/","http://uk.soccerway.com/matches/2017/02/22/england/championship/bristol-city-fc/fulham-football-club/2247116/head2head/"]

urllist中的第二个值将被删除,因为它包含值India,并且它不在国家列表中,从而给出以下最终结果:

urllist = ["http://uk.soccerway.com/matches/2017/02/22/germany/oberliga/tus-mechtersheim-1914/hertha-wiesbach/2300594/head2head/","http://uk.soccerway.com/matches/2017/02/22/england/championship/bristol-city-fc/fulham-football-club/2247116/head2head/"]

Tags: comhttp列表国家matchesuktusgermany
3条回答

您可以使用成员资格运算符in来查看字符串是否包含子字符串。所以,循环遍历country,并检查每个元素是否在urllist中的每个url中。你知道吗

[url for c in country for url in urllist if c in url]

您应该在这里使用split函数,然后检查url中指定的国家是否允许。你知道吗

s  = 'http://a/date/france/other' 
country = s.split('/')[4] #Adapt this to your case
countries = ["england","france","germany"]

interesting_urls = [url for url in urllist if url.split('/')[4] in countries]

这将避免验证一个国家,因为一个印度链接可能涉及一个带有“英格兰”的主题。你知道吗

简单的列表理解将实现这一点:

output = [i for k in country for i in urllist if k in i]

相关问题 更多 >