Ajax
Ajax

Reputation: 179

Iterate on the elements of nested list at particular index together with index of element of another normal list

I have these two lists:

date_list = ['01-01-2020', '01-02-2020', '01-03-2020', '01-04-2020']

values_list = [['00:00:00', '20', '1', '5000'],
 ['00:01:00', '23', '70', '6000', '00:02:00', '56', '48', '8000'], 
['00:03:00', '32', '90', '5800', '00:04:00', '666', '486', '9000'], 
['00:05:00', '776', '68', '950']]

I want that the date get added to every time values like this:

[['01-01-2020 00:00:00', '20', '1', '5000'], 
['01-02-2020 00:01:00', '23', '70', '6000', '01-02-2020 00:02:00', '56', '48', '8000'], 
['01-03-2020 00:03:00', '32', '90', '5800', '01-03-2020 00:04:00', '666', '486', '9000'], 
['01-04-2020 00:05:00', '776', '68', '950']]

I have time at every 27th index in my original values list. I am doing this till now, that i add date to every element of nested list and then use pandas to clear it after.

[ [date_list[i] + ' '+ j for j in sub] for i, sub in enumerate(values_list) ]

Any optimal way to do this?

Upvotes: 0

Views: 47

Answers (3)

Suraj
Suraj

Reputation: 2477

ans = [[v if ':' not in v else dl+' '+v for v in vl] for dl,vl in zip(date_list, values_list)]

The code appends the date to all attributes that have a : which only dates have.

Output :

[['01-01-2020 00:00:00', '20', '1', '5000'],
 ['01-02-2020 00:01:00',
  '23',
  '70',
  '6000',
  '01-02-2020 00:02:00',
  '56',
  '48',
  '8000'],
 ['01-03-2020 00:03:00',
  '32',
  '90',
  '5800',
  '01-03-2020 00:04:00',
  '666',
  '486',
  '9000'],
 ['01-04-2020 00:05:00', '776', '68', '950']]

Upvotes: 1

superb rain
superb rain

Reputation: 5521

I'd use a loop.

for date, values in zip(date_list, values_list):
    values[::4] = (date + ' ' + value for value in values[::4])

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

I'd zip both data together (not combine them) and rebuild the list, altering the element if matches date (every 4th element), keeping others

result = [["{} {}".format(dl,x) if i%4==0 else x for i,x in enumerate(vl)]
           for dl,vl in zip(date_list,values_list)]

>>> result
[['01-01-2020 00:00:00', '20', '1', '5000'],
 ['01-02-2020 00:01:00',
  '23',
  '70',
  '6000',
  '01-02-2020 00:02:00',
  '56',
  '48',
  '8000'],
 ['01-03-2020 00:03:00',
  '32',
  '90',
  '5800',
  '01-03-2020 00:04:00',
  '666',
  '486',
  '9000'],
 ['01-04-2020 00:05:00', '776', '68', '950']]

Upvotes: 1

Related Questions