Home > Net >  Convert a List of Lists that contains integers into a string based on ascii value
Convert a List of Lists that contains integers into a string based on ascii value

Time:10-18

How would I convert a 2D list of integers into a string based on the ascii value? For example, I input [ [97,97,97], [98,98,98] ] and I want the output to be ['aaa', 'bbb']

def to_string2(a):
   for subarr in a:
       for ele in subarr:
           ''.join(chr(i) for i in ele)

I have the following code, which I've just been typing randomly just to see if I could get something to work, since I don't have a clue on how to do it. Any help would be greatly appreciated.

CodePudding user response:

You can use list comprehension:

lst = [[97,97,97], [98,98,98]]

output = [''.join(map(chr, sublst)) for sublst in lst]
print(output) # ['aaa', 'bbb']

Your code has an excessive level of for loop:

output = []
for sublst in lst:
   output.append(''.join(chr(i) for i in sublst))

would work.

CodePudding user response:

Nesting two .join should do the job. Try this:

' '.join([''.join([str(el) for el in subarr]) for subarr in arr])

CodePudding user response:

You'r doing one too much iteration

  • iterate over each sublist for subarr in a
  • iterate over each int for ele in subarr
  • ! ! ! you can't iterate over the int for i in ele
def to_string2(a):
    result = []
    for subarr in a:
        result.append(''.join(chr(ele) for ele in subarr))
    return result

CodePudding user response:

def to_string2(a):
    return ["".join([chr(i) for i in subarr]) for subarr in a]


print(to_string2([[97,97,97], [98,98,98]]))
  • Related