anonymous33243433
anonymous33243433

Reputation: 31

Combine two strings in a list

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

I basically have a date and energy production as a int after it. I want to make it so that it looks like

['2016-01-01 00:00:00;0',
 '2016-01-01 08:00:00;268705.0',
 ... etc]

aka ['date;energy']

Any tips? I am new to this and need this to get through my course...

Upvotes: 3

Views: 54

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51633

Use zip() and list-slicing to zip every 2nd element starting at index 0 with every 2nd element starting at index 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)

Output:

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

If I were you I would not str-combine them , but work further using the tuples. F.e. if you want to summ up energies per day:

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)

Output:

[('2016-01-01', 268705.0), ('2016-01-02', 0.0), ('2016-01-03', 18.05)]

Upvotes: 3

Albin Paul
Albin Paul

Reputation: 3419

use a zip to generate a zipped list of your needed values and then use join to join the list with a ;

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

Upvotes: 1

Related Questions