这是我的清单:
matched_rows_2 =[
['1', '07-09-2020', '8:43:02', '100', 'TTF'],
['2', '07-09-2020', '8:43:02', '100', 'GGY'],
['3', '07-09-2020', '7:53:08', '120', 'HHJ'],
['4', '07-09-2020', '7:54:01', '160', 'JJH'],
['5', '07-09-2020', '8:30:00', '160', 'RRT'],
['6', '07-09-2020', '10:10:10', '160', 'PPO'],
['7', '07-09-2020', '11:12:11', '100', 'KKG'],
['8', '07-09-2020', '11:31:55', '160', 'PPO']]
我正在尝试执行以下操作:
index[3]
),我试图获得一个日期时间最接近chosen_datetime
的列表李>我试过很多方法,但似乎还不起作用以下是我的code:
chosen_datetime = datetime.fromisoformat("2020-07-09 08:43:55+00:00")
dts = [datetime.strptime(sub[1] + ' ' + sub[2], "%d-%m-%Y %H:%M:%S").replace(tzinfo=timezone.utc) for sub in matched_rows_2]
for x in matched_rows_2:
closest_to_chosen_datetime = min(dts, key=lambda d: max( d, chosen_datetime) - min(d, chosen_datetime))
if closest_to_chosen_datetime:
print(x)
这是我想要的输出:
['1', '07-09-2020', '8:43:02', '100', 'TTF'],
['2', '07-09-2020', '8:43:02', '100', 'GGY'],
['3', '07-09-2020', '7:53:08', '120', 'HHJ'],
['5', '07-09-2020', '8:30:00', '160', 'RRT'],
这是我当前的输出:
['1', '07-09-2020', '8:43:02', '100', 'TTF'],
['2', '07-09-2020', '8:43:02', '100', 'GGY'],
['3', '07-09-2020', '7:53:08', '120', 'HHJ'],
['4', '07-09-2020', '7:54:01', '160', 'JJH'],
['5', '07-09-2020', '8:30:00', '160', 'RRT'],
['6', '07-09-2020', '10:10:10', '160', 'PPO'],
['7', '07-09-2020', '11:12:11', '100', 'KKG'],
['8', '07-09-2020', '11:31:55', '160', 'PPO']]
我真的不知道发生了什么,出了什么问题
第一个问题是在循环中有一个
print
命令。由于在遍历所有项之后才知道哪些行的日期时间最接近chosen_datetime
,因此这是过早的,也是导致输出错误的一个重要原因其次,因为您要查找每辆车最近的日期时间 数字您需要一些逻辑来按车辆分组 号码
一种选择是使用
itertools.groupby
的解决方案;另一个 我在这里实现的解决方案是将结果存储在 由车辆编号键入的字典下面的代码中有一些注释,但是如果 你需要一些额外的细节
运行上述程序会产生以下输出:
相关问题 更多 >
编程相关推荐