【发布时间】:2020-10-15 06:41:40
【问题描述】:
我有一个文件,如果满足 2 个条件,我想将一些行附加到一个空列表中:
- 我只选取具有
country_code的行,my_countrycodesAND 中也存在该行 - 对于每个
country_code,如果该日期时间为my_time1,我将取最大日期时间
请注意,文件中每一行的country_code 索引为[1],每一行的日期时间是一个名为date_time4 的变量。
这是我的代码:
my_time = '2020-09-06 16:00:45'
my_time1 = datetime.datetime.strptime(my_time, '%Y-%m-%d %H:%M:%S')
my_countrycodes = ['555', '256', '1000']
all_row_times = [] #<--- this is the list where we will append the datetime values of the file
new_list = [] #<--- this is the final list where we will append our results
with open(root, 'r') as out:
reader = csv.reader(out, delimiter = '\t')
for row in reader:
# print(row)
date_time1 = row[-2] + row[-1] #<--- concatenate date + time
date_time2 = datetime.datetime.strptime(date_time1, '%d-%m-%Y%H:%M:%S') #<--- make a datetime object of the string
date_time3 = datetime.datetime.strftime(date_time2, '%Y-%m-%d %H:%M:%S') #<--- turn the datetime object back to a string
date_time4 = datetime.datetime.strptime(date_time3, '%Y-%m-%d %H:%M:%S') #<--- turn the string object back to a datetime object
all_row_times.append(date_time4) #<--- put all the datetime objects into a list.
if any(country_code in row[1] for country_code in my_countrycodes) and date_time4 == max(dt for dt in all_row_times if dt < my_time1):
new_list.append(row) #<-- append the rows with the same country_code in my_countrycodes and the latest time if that time is < my_time1
print(new_list)
文件如下所示: enter image description here
这是new_list的输出:
[['USA', '555', 'White', 'True', 'NY', '06-09-2020', '10:11:32'],
['USA', '555', 'White', 'True', 'BS', '06-09-2020', '10:11:32'],
['EU', '256', 'Blue', 'False', 'BR', '06-09-2020', '11:26:21'],
['GE', '1000', 'Green', 'True', 'BE', '06-09-2020', '14:51:45'],
['GE', '1000', 'Green', 'True', 'BE', '06-09-2020', '15:59:45']]
如您所见,代码提取具有country_codes555、256 和1000 的行,它还提取小于my_time1 的行。所以这部分工作完美。但是,1000 行有 2 个不同的日期时间,我不明白为什么它不只占用 MAX 日期时间。
这是new_list的预期输出:
[['USA', '555', 'White', 'True', 'NY', '06-09-2020', '10:11:32'],
['USA', '555', 'White', 'True', 'BS', '06-09-2020', '10:11:32'],
['EU', '256', 'Blue', 'False', 'BR', '06-09-2020', '11:26:21'],
['GE', '1000', 'Green', 'True', 'BE', '06-09-2020', '15:59:45']]
【问题讨论】: