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

时间:2016-06-24 21:01:47

标签: python string list python-2.7

我有字符串列表:

['[12 9 15]','[98 12 18]','[56 45 45]']   

我希望将其转换为

[[12,9,15],[98,12,18],[56,45,45]]

6 个答案:

答案 0 :(得分:6)

您可以在split内使用list comprehension来执行此操作。

由于[1 2 3]不是字符串中python列表的正确表示,我们可以删除括号以获得'1 2 3',其中分割变为['1', '2', '3']。通过使用int callable将其强制转换为int,可以很容易地将其转换为整数嵌套列表。

>>> l = ['[12 9 15]','[98 12 18]','[56 45 45]']   
>>> [[int(j) for j in i[1:-1].split()] for i in l]
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]

进一步阅读What does "list comprehension" mean? How does it work and how can I use it?

答案 1 :(得分:2)

您的字符串[12 9 15]的格式不像python列表(缺少逗号)。根据解析器需要的强大程度,您可以选择几个选项:

import ast
out_list = []
for string_list in list_of_strings:
    list_repr = ','.join(string_list.split())
    out_list.append(ast.literal_eval(list_repr))

只要您没有任何格式如下的内部字符串,这将有效。

'[ 12 9, 5](领先的空间会弄乱它)

我认为可能我认为最强大的解析器是删除[]并自己解析它:

out_list = []
for string_list in list_of_strings:
    str_items = string_list.replace('[', '').replace(']', '')
    out_list.append([int(item) for item in str_items.split()])

答案 2 :(得分:2)

只要字符串相当规则,这应该有效:

>>> x = ['[12 9 15]','[98 12 18]','[56 45 45]']   
>>> x = [[int(i) for i in string.strip('[]').split()] for string in x]
>>> x
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]

答案 3 :(得分:1)

使用正则表达式

[map(int, re.findall('\d+', item)) for item in x]

如果它并不总是格式良好。

>>> import re
>>> [map(int, re.findall('\d+', item)) for item in x]
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]

答案 4 :(得分:0)

解决方案越简单,其他人就越能理解。

这是我的解决方案:

list_of_strings =  ['[12 9 15]','[98 12 18]','[56 45 45]']  
list_of_lists = [map(int, x[1:-1].split()) for x in list_of_strings]

所以我在这里使用list-comprehension。地图'函数返回一个列表。代码x[1:-1].split()将在空格字符上拆分每个字符串,然后每个字符串标记将转换为' int'这是我传递给地图功能的功能。

需要对我的代码进行更多解释吗?

答案 5 :(得分:0)

请检查这是否有用。

>>> x = ['[12 9 15]','[98 12 18]','[56 45 45]']
>>> print eval(str([ item.replace(" ",",") for item in x ]).replace("'", ''))
[[12, 9, 15], [98, 12, 18], [56, 45, 45]]
相关问题