gpt4 book ai didi

python - 将日期时间对象附加到列表,按形状分组

转载 作者:太空宇宙 更新时间:2023-11-03 15:39:40 25 4
gpt4 key购买 nike

我有这个代码:

from datetime import datetime

values = [[datetime(2017, 1, 22, 10, 2, 11, 170913), datetime(2017, 1, 22, 10, 3, 11, 170913),
datetime(2017, 1, 2, 10, 4, 11, 170913), datetime(2017, 1, 22, 10, 5, 11, 170913)],
[datetime(2017, 1, 22, 10, 1, 11, 170913), datetime(2017, 1, 22, 10, 2, 11, 170913),
datetime(2017, 1, 22, 10, 3, 11, 170913), datetime(2017, 1, 22, 10, 4, 11, 170913)]]

secs = []
secs.append([i.timestamp() for t in values for i in t])
print(secs)

输出是:

[[1485072131.170913, 1485072191.170913, 1483344251.170913, 1485072311.170913, 1485072071.170913, 1485072131.170913, 1485072191.170913, 1485072251.170913]]

我希望输出像输入(值)形状一样:

[[1485072131.170913, 1485072191.170913, 1483344251.170913, 1485072311.170913], 
[1485072071.170913, 1485072131.170913, 1485072191.170913, 1485072251.170913]]

我知道我可以对结果进行 reshape ,但是当我附加时还有其他方法吗?

最佳答案

简单地让你的列表理解嵌套而不是平面:

secs = [[i.timestamp() for i in t] for t in values]
print(secs)

你会得到你想要的:

[[1485097331.170913, 1485097391.170913, 1483369451.170913, 1485097511.170913], 
[1485097271.170913, 1485097331.170913, 1485097391.170913, 1485097451.170913]]

关于python - 将日期时间对象附加到列表,按形状分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42273326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com