简体   繁体   中英

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 :

  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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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