如何检查列表或n中存在的多个分隔字符串

2024-09-27 23:17:14 发布

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

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

我试过了

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")

Tags: 字符串in列表iflocationlistprintstr
3条回答

这里我给你一个正确的实现例子。你知道吗

location = ["Bangalore", "Delhi"]
locations_list = ["Bangalore", "Delhi", "Mumbai", "Hyderabad", "Uttar Pradesh"]
for location in location :
    for ref in locations_list:
        if location == ref:
            print(f"{location} present in locations list")

这是对你的任务的一个典型的概括。但是,正如您所知,嵌套循环的性能很差。你知道吗

所以。。。我给你一个更好的实现:

    location = ["Bangalore", "Delhi"]
locations_list = ["Bangalore", "Delhi", "Mumbai", "Hyderabad", "Uttar Pradesh"]
[print(f"{location} present in locations list") for location in location for ref in locations_list if (location == ref)]

在这段代码中,我使用列表理解来稍微提高性能,但概念是相同的。检查第一个列表中的每个项目,并将其与另一个列表中的每个项目进行比较。你知道吗

也许你可以提高你的表现,每次你得到一个匹配的继续。你知道吗

我知道这并不是执行这种搜索的最佳方式,但它们都很简单而且可以运行。你知道吗

PD:我已经使用了python3.6+,如果你想在较低版本中运行代码,只需在字符串之前去掉f

在代码中,检查list是否在str中,而不是str是否在list中。你知道吗

更改代码如下:

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

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

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")

相关问题 更多 >

    热门问题