繁体   English   中英

如何测试字符串是否部分包含在 Python 的列表中

[英]How to test if a string is partialy contained in a list in Python

我有清单:

list1 = ['tom.frank.phillips','jimmy.fund.roberts','markus.shane.sherman','glen.carl.smith']

我正在尝试测试以下名称是否包含在此列表中的任何位置:

nameslist = ['shane', 'frank', 'dale', 'roberts', 'smith', 'tony']

如果它们不包含在原始列表中的任何位置,那么我想打印名称。

我努力了:

for name in nameslist:
    if name not in list1:
        print(name)

但是当我这样做时,所有的名字都会被打印出来。

这些名称都不是list1的元素。 您需要检查名称是否是list1的任何元素的子字符串。

if not any(name in full_name for full_name in list1):
    print(name)

另一种方法是简单地连接所有长名称; 然后in该单个字符串上使用:

all_names = ' '.join(list1)
for name in names list:
    if not name in all_names:
        print(name)

暂无
暂无

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

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