2

I have a list of strings representing dates:

>>> dates
['14.9.2016',
 '13.9.2016',
 '12.9.2016',
 '11.9.2016',
 '10.9.2016',
 '9.9.2016',
 '8.9.2016',
 '7.9.2016',
 '6.9.2016',
 '5.9.2016']

I need to zero-padd days & months and I cannot use standard calendar methods due to "artifical dates" I need to work with ("29.2.2015" for example)

following seems to be working:

>>> parsed_dates = []
>>> for l in [d.split('.') for d in dates]:
>>>    parsed_dates.append('.'.join([i.zfill(2) for i in l]))

>>> parsed_dates
['14.09.2016',
 '13.09.2016',
 '12.09.2016',
 '11.09.2016',
 '10.09.2016',
 '09.09.2016',
 '08.09.2016',
 '07.09.2016',
 '06.09.2016',
 '05.09.2016']

is it possible to achieve the same result using a single list comprehension? or some other, more elegant way? I have tried following, but cannot find a way to concatenate single list items to form date strings again...

>>> [i.zfill(2) for l in [d.split('.') for d in dates] for i in l]
['14',
 '09',
 '2016',
 '13',
 '09',
 '2016',
 '12',
 '09',
.
.
.

1 Answer 1

7

Sure, just inline the expression you pass to the parsed_dates.append() call, with l substituted with d.split('.') from your for loop:

['.'.join([i.zfill(2) for i in d.split('.')]) for d in dates]

Demo:

>>> ['.'.join([i.zfill(2) for i in d.split('.')]) for d in dates]
['14.09.2016', '13.09.2016', '12.09.2016', '11.09.2016', '10.09.2016', '09.09.2016', '08.09.2016', '07.09.2016', '06.09.2016', '05.09.2016']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.