Convert a number in the list to text

Asked 2 years ago, Updated 2 years ago, 14 views

Given a list such as [1, 2, 3, 4],

1 = '1'
2 = '2'
3 = 'a'
4 = 'b'

Is there a way to return specific characters to a specific number?

The desired result value is ['1','2','a','b'] -> Finally, I want to print it as '12ab'.

I think we should approach it by assigning one by one, but I don't have a clue.

python

2022-09-20 17:47

2 Answers

There is a mapping for 1, 2, 3, and 4, and you want to join the result after the mapping.


>>> l = [ 1, 2, 3, 4 ]
>>> map_table = { 1:"1", 2:"2", 3:"a", 4:"b" }
>>> mapped = [ map_table[e] for e in l ]
>>> mapped
['1', '2', 'a', 'b']
>>> ''.join(mapped)
'12ab'
>>> 
>>> 
>>> def map_join(l: list):
    return ''.join(map_table[e] for e in l)

>>> map_join([1,2,3,4])
'12ab'
>>> map_join([2,3,1,2])
'2a12'
>>> map_join([1,1,1,1])
'1111'
>>> 


2022-09-20 17:47

I don't know exactly what you want. First of all, the questions can be implemented as follows.

list1 = [1, 2, 3, 4]

a = ''
for i in list1:
    if i == 1:
        a += '1'
    elif i == 2:
        a += '2'
    elif i == 3:
        a += 'a'
    elif i == 4:
        a += 'b'

print(a)
>> '12ab'

Or

list1 = [1, 2, 3, 4]
dict1 = {1:'1', 2:'2', 3:'a', 4:'b'}

a = ''
for i in list1:
    a += dict1[i]

print(a)
>> '12ab'


2022-09-20 17:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.