简体   繁体   English

将整数列表的列表转换为字符串列表

[英]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: 我得到print(string1)的输出为:

[2, 8]

What am i doing wrong here? 我在这做错了什么?

You actually don't have a list of list , you have a list of str . 你实际上没有list list ,你有一个str list Therefore you can use ast.literal_eval to interpret each string as a list, then convert to str and join . 因此,您可以使用ast.literal_eval将每个字符串解释为列表,然后转换为strjoin

>>> 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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