['2016-01-01 00:00:00', '0',
'2016-01-01 08:00:00', '268705.0',
'2016-01-01 16:00:00', '0',
'2016-01-02 00:00:00', '0',
'2016-01-02 08:00:00', '0.0',
'2016-01-02 16:00:00', '0.0',
'2016-01-03 00:00:00' ...
... etc for 1 year]
基本上,我将日期和能量产生作为一个整数。我要使它看起来像
['2016-01-01 00:00:00;0',
'2016-01-01 08:00:00;268705.0',
... etc]
又名['date;energy']
有什么提示吗?我对此并不陌生,需要它来完成我的课程...
答案 0 :(得分:3)
使用zip()和列表切片可从索引0开始压缩每个第二元素,而从索引1开始压缩每个第二元素。
data = ['2016-01-01 00:00:00', '0',
'2016-01-01 08:00:00', '268705.0',
'2016-01-01 16:00:00', '0',
'2016-01-02 00:00:00', '0',
'2016-01-02 08:00:00', '0.0',
'2016-01-02 16:00:00', '0.0',
'2016-01-03 00:00:00', "18.05",]
new_data = list(zip(data[0::2],data[1::2]))
print(new_data)
combined = ["{};{}".format(a,b) for a,b in new_data]
print(combined)
输出:
# new_data (I would vouch to use that further on)
[('2016-01-01 00:00:00', '0'), ('2016-01-01 08:00:00', '268705.0'),
('2016-01-01 16:00:00', '0'), ('2016-01-02 00:00:00', '0'),
('2016-01-02 08:00:00', '0.0'), ('2016-01-02 16:00:00', '0.0'),
('2016-01-03 00:00:00', '18.05')]
# combined
['2016-01-01 00:00:00;0', '2016-01-01 08:00:00;268705.0', '2016-01-01 16:00:00;0',
'2016-01-02 00:00:00;0', '2016-01-02 08:00:00;0.0', '2016-01-02 16:00:00;0.0',
'2016-01-03 00:00:00;18.05']
如果我是你,我不会str-combine他们,而是进一步使用元组。 F.e.如果您想每天汇总能量:
new_data = sorted((zip(data[0::2],data[1::2])))
from itertools import groupby
# x[0][0:10] uses the 1st element of each tuple (the datetime) and slices only the date
# from it. That is used to group all data.
k = groupby(new_data, lambda x:x[0][0:10])
summs = []
for date,tups in k:
summs.append( (date,sum(float(x[1]) for x in tups)) )
print(summs)
输出:
[('2016-01-01', 268705.0), ('2016-01-02', 0.0), ('2016-01-03', 18.05)]
答案 1 :(得分:1)
使用zip
生成所需值的压缩列表,然后使用join
将列表与;
结合起来
>>> a=['2016-01-01 00:00:00', '0', '2016-01-01 08:00:00', '268705.0', '2016-01-01 16:00:00', '0']
>>> [';'.join(i) for i in zip(a[::2],a[1::2])]
['2016-01-01 00:00:00;0', '2016-01-01 08:00:00;268705.0', '2016-01-01 16:00:00;0']
>>>