Python性能优化:校验两列表对应索引元素是否同存于字符串
高效校验对应邮政编码与城市是否同时存在于文本中的方法
我从CSV文件中获取了两个列表:column1为邮政编码(ZIP codes),column2为城市名称(City Name)。另有一段包含随机文本的字符串,可能包含邮政编码和城市名称。需要校验每个索引i对应的column1[i]和column2[i]是否同时存在于该字符串中。
我曾使用过一种单列表校验方案,但它仅能校验单个列表的元素是否存在于字符串中,且不会返回原列表的索引位置,无法匹配对应索引的城市名称。
目前我使用的代码如下:
for i in range(39000): if all(map(lambda w: w in text, (column1[i], column2[i]))): print(column1[i], column2[i])
处理两个各含3.9万元素的列表时,这段代码耗时约0.3秒。而上述单列表校验方案的耗时仅为0.13-0.17秒,效率是当前实现的两倍。请问有没有更高效的实现方法?
可复现示例
以下是完整测试代码(CSV文件为官方邮政编码数据库):
import pandas as pd column_names = ["code_commune_insee","nom_de_la_commune", "code_postal","ligne_5","libelle_d_acheminement","coordonnees_gps"] df = pd.read_csv("laposte_hexasmal.csv", names=column_names, delimiter=';') column1 = df.code_postal.to_list() column2 = df.nom_de_la_commune.to_list() # 短列表测试用例 column1_short_version_example = ['48283', '43288', '84389', '403294', '84384', '88439'] column2_short_version_example = ['PARIS', 'Paris', 'London', 'Amsterdam', 'Dublin', 'Manchester'] text = 'Hello, yes your order is indeed confirmed for the 14th in our hotel neer PARIS 12, the zip code is 43288 or 75012, if you want to book a night in London two weeks after, we still have room avaible, the postal code for the hotel address is 45 road street 84389' for i in range(len(column1)): if all(map(lambda w: w in text, (column1[i], column2[i]))): print(column1[i], column2[i])
预期结果
- 短列表版本输出:
43288 Paris 84389 London
- CSV文件列表版本输出:
75012 PARIS 12
内容的提问来源于stack exchange,提问作者Darkmoon
相关产品推荐
相关产品推荐

