Convert A List Of Integer To A List Of Predefined Strings In Python
How to convert a list [0,1,2,1] to a list of string, when we convert 0 to 'abc', 1 to 'f' and 2 to 'z'? So the output list will be ['abc','f','z','f']. I did: x = [] for i in xrang
Solution 1:
Use a dictionary as your translation table:
old_l = [0, 1, 2, 1]
trans = {0: 'abc', 1: 'f', 2: 'z'}
Then, to translate your list:
new_l = [trans[v] for v in old_l]
Solution 2:
As an alternative to a dict, if you can guarantee that the numbers are sequential, you can just use a list and indexes:
subs = ['abc','f','z']
original = [0, 1, 2, 1]
result = [subs[x] for x in original]
Same idea as the dict, but marginally less to type?
Post a Comment for "Convert A List Of Integer To A List Of Predefined Strings In Python"