将datetime对象追加到列表中,按形状分组

时间:2017-02-16 11:58:40

标签: python numpy

我有这段代码:

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]]

我知道我可以对结果进行重塑,但是当我追加时,还有另一种方法吗?

1 个答案:

答案 0 :(得分:1)

简单地使列表理解嵌套而不是平坦:

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]]