简体   繁体   English

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

[英]Convert string of list to list

I have the list of strings: 我有字符串列表:

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

and I want to convert it to 我想把它转换成

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

You can use split inside a list comprehension to do this. 您可以在列表推导中使用split来执行此操作。

As [1 2 3] is not the proper representation of a python list in a string, we can remove the brackets to get '1 2 3' which on splitting becomes ['1', '2', '3'] . 由于[1 2 3]不是字符串中python列表的正确表示,我们可以删除括号以获得'1 2 3' ,在分裂时变为['1', '2', '3'] This can be easily converted to a integer nested list by casting it to an int using the int callable. 通过使用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]]

For further reading What does "list comprehension" mean? 进一步阅读“列表理解”是什么意思? How does it work and how can I use it? 它是如何工作的,我该如何使用它?

Your strings [12 9 15] aren't formatted like python lists (commas are missing). 你的字符串[12 9 15]的格式不像python列表(缺少逗号)。 You've got a couple options depending on how robust your parser needs to be: 根据解析器需要的强大程度,您可以选择几个选项:

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))

This will work so long as you don't have any inner strings formatted like: 只要您没有任何格式如下的内部字符串,这将起作用:

'[ 12 9, 5] (the leading space will mess it up) '[ 12 9, 5] (领先的空间会弄乱它)

I think that probably the most robust parser that I can think of is to remove the [ and ] and them parse it yourself: 我认为可能我能想到的最强大的解析器是删除[]并自己解析它:

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()])

As long as the strings are fairly regular, this should work: 只要字符串相当规则,这应该工作:

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

Use a regular expression 使用正则表达式

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

In case it is not always well-formated. 如果它并不总是格式良好。


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

The simpler the solution, the better it is for others to understand. 解决方案越简单,其他人理解的越好。

Well here is my solution: 那么这是我的解决方案:

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]

So I using list-comprehension here. 所以我在这里使用list-comprehension。 The 'map' function returns a list. 'map'函数返回一个列表。 The code x[1:-1].split() will split each string on space character(s) and the each string token would then be converted to 'int' which is the function I've passed to the map function. 代码x[1:-1].split()将在空格字符上拆分每个字符串,然后每个字符串标记将转换为'int',这是我传递给map函数的函数。

Need more explanation over my code? 需要更多解释我的代码?

Please check if this is helpful. 请检查这是否有用。

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

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

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