【发布时间】:2021-05-06 20:59:12
【问题描述】:
这是我的文件:
#This is TEST-data
2020-09-07T00:00:03.230+02:00,ID-10,3,Lon,Man,Lon,1,1,1
2020-09-07T00:00:03.230+02:00,ID-10,3,Lon,Lon,Man,1,1
2020-09-07T00:00:03.230+02:00,ID-20,2,Lon,Lon,1,1
2020-09-07T00:00:03.230+02:00,ID-20,2,Lon,Lon,1
2020-09-07T00:00:03.230+02:00,ID-30,3,Mad,Sev,Sev,1,1,1
2020-09-07T00:00:03.230+02:00,ID-30,GGG,Mad,Sev,Mad1
2020-09-07T00:00:03.230+02:00,ID-40,GGG,Mad,Bar,1,1,1,1
2020-09-07T00:00:03.230+02:00
2020-09-07T00:00:03.230+02:00
当我运行下面的代码时,我得到一个空返回。那可能是因为我的代码似乎不知道 Man 在曼彻斯特,而 Sev 在塞维利亚。
我认为问题出在condition_1
path = r'c:\data\ELK\Desktop\test_data_countries.txt'
cities_to_filter = ['Sevilla', 'Manchester']
def filter_row(row):
if len(row) > 2 and row[2].isdigit():
amount_of_cities = int(row[2])
cities_to_check = row[3:3+amount_of_cities]
condition_1 = any(city in cities_to_check for city in cities_to_filter)
return condition_1
with open (path, 'r') as output_file:
reader = csv.reader(output_file, delimiter = ',')
next(reader)
for row in reader:
if filter_row(row):
print(row)
这是我的预期输出:
2020-09-07T00:00:03.230+02:00,ID-10,3,Lon,Man,Lon,1,1,1
2020-09-07T00:00:03.230+02:00,ID-10,3,Lon,Lon,Man,1,1
2020-09-07T00:00:03.230+02:00,ID-30,3,Mad,Sev,Sev,1,1,1
【问题讨论】:
-
您的代码正在检查“Manchester”是否在“Man”中,而应该是相反的。
-
它总是会是名称中的前 3 个字符,例如 Man 代表曼彻斯特,还是有可能出现 Mhr 或 Mcr 代表曼彻斯特。
-
@SandeepKumar 可能会有所不同。并不总是前 3 个。
-
@TangerCity 那么我可能会做什么,因为这些是以逗号分隔的值将它们加载到熊猫数据框中并检查不同的可能性,并可能保留一个字典(一种地图 Man -> Manchester)。可能还有其他方法可以提高效率。
标签: python list if-statement filter