如果我有这样的列表:
lst = [['00:10:00', '00:08:00'], ["00:05:00', '00:04:00']]
如何减去每个列表的第一个和第二个数字,并将结果附加到每个列表的末尾,这样我就可以得到:
lst = [['00:10:00', '00:08:00', '00:02:00'], ['00:05:00', '00:04:00', '00:01:00']]
我当前的代码:
end_lst = []
lst = [['00:10:00', '00:08:00'], ['00:05:00', '00:04:00']]
for t1, t2 in lst:
d1 = datetime.datetime.strptime(t1, "%H:%M:%S")
d2 = datetime.datetime.strptime(t2, "%H:%M:%S")
diff = (d2 - d1)
end_lst = [item + [diff] for item in lst]
print(end_lst)
,但每个列表的输出均不正确。有什么想法吗?
输出:
[['00:10:00', '00:08:00', datetime.timedelta(-1, 86160)], ['00:05:00', '00:04:00', datetime.timedelta(-1, 86160)]]
答案 0 :(得分:1)
以下内容如何?
导入日期时间
end_lst = []
lst = [['00:10:00', '00:08:00'], ['00:05:00', '00:04:00']]
for tup in lst:
d1 = datetime.datetime.strptime(tup[0], "%H:%M:%S")
d2 = datetime.datetime.strptime(tup[1], "%H:%M:%S")
diff = (d1 - d2)
end_lst = [item + [str(diff)] for item in lst]
print(end_lst)
答案 1 :(得分:1)
如果您将每个元素都视为一个列表,而又没有拆包,那将非常简单:
lst = [['00:10:00', '00:08:00'], ['00:05:00', '00:04:00']]
for internal_list in lst:
d1 = datetime.datetime.strptime(internal_list[0], "%H:%M:%S")
d2 = datetime.datetime.strptime(internal_list[1], "%H:%M:%S")
diff = (d2 - d1)
internal_list.append(diff)
print(lst)
答案 2 :(得分:1)
只需将datetime.timedelta
对象转换为字符串,同时确保从d1
中减去d2
。
lst = [['00:10:00', '00:08:00'], ['00:05:00', '00:04:00']]
for t1, t2 in lst:
d1 = datetime.datetime.strptime(t1, "%H:%M:%S")
d2 = datetime.datetime.strptime(t2, "%H:%M:%S")
diff = str(d1 - d2) # Only change to your current source code
end_lst = [item + [diff] for item in lst]
print(end_lst) # [['00:10:00', '00:08:00', '0:02:00'], ['00:05:00', '00:04:00', '0:01:00']]
受@ferhen的启发,尽管可以说可读性被牺牲了,但是您也可以使用列表理解来使其更加简洁。
end_lst = [[t1, t2, str(datetime.datetime.strptime(t1, "%H:%M:%S") - datetime.datetime.strptime(t2, "%H:%M:%S"))] for t1, t2 in lst]
print(end_lst) # [['00:10:00', '00:08:00', '0:02:00'], ['00:05:00', '00:04:00', '0:01:00']]
现在,这是假设t1
表示晚于t2
的时间。如果没有,您的嵌套列表中可能会得到诸如'-1 day, 23:59:00'
之类的结果。
答案 3 :(得分:0)
一支班轮
end_lst = [[t1, t2, str(datetime.datetime.strptime(t1, "%H:%M:%S") - datetime.datetime.strptime(t2, "%H:%M:%S"))] for (t1, t2) in lst]
答案 4 :(得分:0)
您的lst
不正确,否则您的代码就可以了。
import datetime
lst = [['00:10:00', '00:08:00'], ["00:05:00", '00:04:00']]
end_lst = []
lst = [['00:10:00', '00:08:00'], ['00:05:00', '00:04:00']]
for t1, t2 in lst:
d1 = datetime.datetime.strptime(t1, "%H:%M:%S")
d2 = datetime.datetime.strptime(t2, "%H:%M:%S")
diff = (d2 - d1)
end_lst = [item + [diff] for item in lst]
print(end_lst)
输出为:
[['00:10:00', '00:08:00', datetime.timedelta(-1, 86340)], ['00:05:00', '00:04:00', datetime.timedelta(-1, 86340)]]
那么我猜的问题是您的timedelta对象。您可以在这里找到文档:datetime documentation。
这是我根据您的示例和正确的编辑创建的Google Colab笔记本。 Colab Notebook