我正在尝试搜索列表中是否存在分隔字符串,例如列表中是否存在多个字符串。如何执行此操作
我试过了
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")
这里我给你一个正确的实现例子。你知道吗
这是对你的任务的一个典型的概括。但是,正如您所知,嵌套循环的性能很差。你知道吗
所以。。。我给你一个更好的实现:
在这段代码中,我使用列表理解来稍微提高性能,但概念是相同的。检查第一个列表中的每个项目,并将其与另一个列表中的每个项目进行比较。你知道吗
也许你可以提高你的表现,每次你得到一个匹配的继续。你知道吗
我知道这并不是执行这种搜索的最佳方式,但它们都很简单而且可以运行。你知道吗
PD:我已经使用了python3.6+,如果你想在较低版本中运行代码,只需在字符串之前去掉f
在代码中,检查
list
是否在str
中,而不是str
是否在list
中。你知道吗更改代码如下:
如果您只对是否存在任何元素感兴趣,我建议您使用集合交点:
编辑:
如果要检查
location
中的所有位置是否都在location_list
,我建议使用集合的issubset
方法:相关问题 更多 >
编程相关推荐