Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - list transformation

Tags:

python

list

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...

like image 322
elfuego1 Avatar asked Mar 13 '09 17:03

elfuego1


People also ask

How do you transform a list in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I map one list to another in Python?

Python provides a nicer way to do this kind of task by using the map() built-in function. The map() function iterates over all elements in a list (or a tuple), applies a function to each and returns a new iterator of the new elements.

How do you map all elements in a list in Python?

Python map() function map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.

What is map () in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.


3 Answers

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...

like image 158
DNS Avatar answered Oct 20 '22 03:10

DNS


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'] 
like image 23
Paolo Bergantino Avatar answered Oct 20 '22 02:10

Paolo Bergantino


I would use a list comprehension myself, but here is another solution using map for those interested...

map(lambda v: "%02d" %v, x)
like image 10
Brian R. Bondy Avatar answered Oct 20 '22 02:10

Brian R. Bondy