【发布时间】:2021-05-06 14:09:35
【问题描述】:
我有一个如下所示的文件:
#This is TEST-data
2020-09-07T00:00:03.230+02:00,ID-10,3,London,Manchester,London,1,1,1
2020-09-07T00:00:03.230+02:00,ID-10,3,London,London,Manchester,1,1
2020-09-07T00:00:03.230+02:00,ID-20,2,London,London,1,1
2020-09-07T00:00:03.230+02:00,ID-20,2,London,London1,1
2020-09-07T00:00:03.230+02:00,ID-30,3,Madrid,Sevila,Sevilla,1,1,1
2020-09-07T00:00:03.230+02:00,ID-30,3,Madrid,Sevilla,Madrid,1
2020-09-07T00:00:03.230+02:00,ID-40,2,Madrid,Barcelona,1,1,1,1
每行中的Index[2] 显示该特定行中有多少城市。所以第一行 index[2] 的值为 3,即London, Manchester, London.
我正在尝试执行以下操作:
对于每一行,我需要检查cities_to_filter. 中是否存在任何行 [3] + 之后提到的城市(基于城市数量)
这是我当前的代码:
path = r'c:\data\ELK\Desktop\test_data_countries.txt'
cities_to_filter = ['Sevilla', 'Manchester']
def filter_row(row):
# amount_of_cities = row[2]
condition_1 = any(city in row 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)
我为这个数据集编写的代码可以正常工作,但由于它查看每一列,即使是我知道的不是城市的列,它也很危险。我需要我的代码根据每行包含的城市数量仅检查属于城市的列。
【问题讨论】:
-
这看起来很有趣。您可以使用
amount_of cities创建一个新的城市列表作为cities_to_filter的一部分。然后您使用该列表与您的cities_to_filter进行比较 -
@NorthAfrican 说起来难,做起来难。我不想在我当前的代码中改变太多。我觉得我真的很亲近。
-
@mhawke 你到底是什么意思?
-
@mhawke 没问题,伙计,也许你仍然可以帮助我。感觉我真的很亲近。
标签: python list indexing filter