[英]Convert String of List of list ..to ..List of List with all individual elements as strings
Input is given in ONE stretch as:输入在一个拉伸中给出:
'[[F1,S1],[F2,S2],[F3,S3],[F1,S2],[F2,S3],[F3,S2],[F2,S1],[F4,S1],[F4,S3],[F5,S1]]'
and I want to convert the "string of a list of lists" into a "list of lists with all individual elements as strings"我想将“列表列表的字符串”转换为“所有单个元素作为字符串的列表列表”
[['F1','S1'],['F2','S2'],['F3','S3'],['F1','S2'],['F2','S3'],['F3','S2'],['F2','S1'],['F4','S1'],['F4','S3'],['F5','S1']]
How to?如何?
I'm going to make the assumption that the input string is always formatted without any whitespace around the characters [
, ,
or ]
.我将假设输入字符串始终被格式化,字符
[
,
或]
周围没有任何空格。 This can be achieved without anything fancy or dangerous like eval
:这可以在没有任何花哨或危险的情况下实现,例如
eval
:
[[
and ]]
from the start and end with a string slice.[[
和]]
,并以字符串切片结尾。],[
which separates the inner lists from each other.],[
将内部列表彼此分开。,
which separates the elements from each other.,
从而将元素彼此分开。 There are two special cases to deal with.有两种特殊情况需要处理。 First, if the outer list is empty, then the string doesn't begin or end with
[[
and ]]
.首先,如果外部列表为空,则字符串不以
[[
和]]
开头或结尾。 Second, if one of the inner lists is empty, the result of split
will produce a list containing a single empty string, when the correct output should be an empty list.其次,如果其中一个内部列表为空,则
split
结果将生成一个包含单个空字符串的列表,此时正确的 output 应该是一个空列表。
def parse_2d_list(s):
if s == '[]':
return []
else:
parts = s[2:-2].split('],[')
return [p.split(',') if p else [] for p in parts]
Output: Output:
>>> parse_2d_list('[[F1,S1],[F2,S2],[F3,S3]]')
[['F1', 'S1'], ['F2', 'S2'], ['F3', 'S3']]
This will be better这会更好
def parse_2d_list(s):
parts = s[2:-2].split('],[')
return [p.split(',') for p in parts]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.