简体   繁体   中英

Convert list of list of integers into a list of strings

I have a list of strings:

['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]']  

I want output to look like

['28','82','253',2530',5302']

I've tried using

string1= ''.join(str(e) for e in list[0])

I get output for print (string1) as:

[2, 8]

What am i doing wrong here?

You actually don't have a list of list , you have a list of str . Therefore you can use ast.literal_eval to interpret each string as a list, then convert to str and join .

>>> l = ['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]']
>>> from ast import literal_eval
>>> [''.join(str(j) for j in literal_eval(i)) for i in l]
['28', '82', '253', '2530', '5302']

If you want to use built-in functions only (without imports), you can define a function that parses only the numbers and map that function to your list.

def remove_non_digits(z):
    return "".join(k if k.isdigit() else "" for k in z)

>>> map(remove_non_digits, a)
['28', '82', '253', '2530', '5302']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM