简体   繁体   English

将列表列表的字符串..转换为..列表的列表,所有单个元素都作为字符串

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

  1. Remove the [[ and ]] from the start and end with a string slice.从开头删除[[]] ,并以字符串切片结尾。
  2. Then, split on ],[ which separates the inner lists from each other.然后,拆分],[将内部列表彼此分开。
  3. Then, split each inner list on , 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.

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