Python – list transformation
Question:
Does anyone knows what magic I have to use to change x list:
x = [1,2,3,4,5,11]
into y list?
y = [’01’,’02’,’03’,’04’,’05’,’11’]
Thank you all in advance for helping me…
Answers:
You want to use the built-in map
function:
>>> x = [1,2,3,4,5]
>>> x
[1, 2, 3, 4, 5]
>>> y = map(str, x)
>>> y
['1', '2', '3', '4', '5']
EDIT You changed the requirements on me! To make it display leading zeros, you do this:
>>> x = [1,2,3,4,5,11]
>>> y = ["%02d" % v for v in x]
>>> y
['01', '02', '03', '04', '05', '11']
You can use a list comprehension (Python 2.6+):
y = ["{0:0>2}".format(v) for v in x]
Or for Python prior to 2.6:
y = ["%02d" % v for v in x]
Or for Python 3.6+ using f-strings:
y = [f'{v:02}' for v in x]
Edit: Missed the fact that you wanted zero-padding…
to get the 0’s:
y = ['%02d' % i for i in x]
y = ['%02d'%v for v in x]
I would use a list comprehension myself, but here is another solution using map for those interested…
map(lambda v: "%02d" %v, x)
An alternative to format strings would be to use the string’s zfill() method:
y = [str(i).zfill(2) for i in x]
Another thing: you might be after padding based on the largest item in the list, so instead of just using 2, you could do:
pad_length = len(str(max(x)))
y = [str(i).zfill(pad_length) for i in x]
Try this:
>>> [str(v).rjust(2,'0') for v in x]
['01', '02', '03', '04', '05', '11']
rjust as a method of string class, takes an integer argument(result length) and an optional padding character
Does anyone knows what magic I have to use to change x list:
x = [1,2,3,4,5,11]
into y list?
y = [’01’,’02’,’03’,’04’,’05’,’11’]
Thank you all in advance for helping me…
You want to use the built-in map
function:
>>> x = [1,2,3,4,5]
>>> x
[1, 2, 3, 4, 5]
>>> y = map(str, x)
>>> y
['1', '2', '3', '4', '5']
EDIT You changed the requirements on me! To make it display leading zeros, you do this:
>>> x = [1,2,3,4,5,11]
>>> y = ["%02d" % v for v in x]
>>> y
['01', '02', '03', '04', '05', '11']
You can use a list comprehension (Python 2.6+):
y = ["{0:0>2}".format(v) for v in x]
Or for Python prior to 2.6:
y = ["%02d" % v for v in x]
Or for Python 3.6+ using f-strings:
y = [f'{v:02}' for v in x]
Edit: Missed the fact that you wanted zero-padding…
to get the 0’s:
y = ['%02d' % i for i in x]
y = ['%02d'%v for v in x]
I would use a list comprehension myself, but here is another solution using map for those interested…
map(lambda v: "%02d" %v, x)
An alternative to format strings would be to use the string’s zfill() method:
y = [str(i).zfill(2) for i in x]
Another thing: you might be after padding based on the largest item in the list, so instead of just using 2, you could do:
pad_length = len(str(max(x)))
y = [str(i).zfill(pad_length) for i in x]
Try this:
>>> [str(v).rjust(2,'0') for v in x]
['01', '02', '03', '04', '05', '11']
rjust as a method of string class, takes an integer argument(result length) and an optional padding character