首页 > 解决方案 > 如何检查列表中是否存在多个逗号分隔的字符串

问题描述

我正在尝试搜索列表中是否存在逗号分隔的字符串,例如列表中是否存在多个字符串。如何执行此操作

我试过这样

location = ["Bangalore", "Delhi"]
locations_list = ["Bangalore", "Delhi", "Mumbai", "Hyderabad", "Uttar Pradesh"]

if any(location in str for str in locations_list ):
    print("location present in locations list")
else:
    print("location not found")

标签: pythonpython-3.x

解决方案


如果您只对是否存在任何元素感兴趣,我建议您使用集合交集:

if set(location) & set(locations_list):
    print("location present in locations list")
else:
    print("location not found")

编辑:

如果您想检查是否所有位置location都在location_list,我建议使用集合的issubset方法:

if set(location).issubset(set(locations_list)):
    print("location present in locations list")
else:
    print("location not found")

推荐阅读