带有字符串值的列表到2D数组

字符串值列表如下所示:

x = ["0: ['17' '19']", "1: ['32' '35']", "2: ['29']", "3: ['16']", "4: ['24' '18' '9']", "6: ['24' '26']", "9: ['11' '26' '34']", "10: ['33']"]

我想要一个2D数组,所以我可以这样做:

print(x[0][1][1])
19

首先,我摆脱了结肠:

x = [i.split(': ') for i in x]
[['0', "['17' '19']"], ['1', "['32' '35']"], ['2', "['29']"], ['3', "['16']"], ['4', "['24' '18' '9']"], ['6', "['24' '26']"], ['9', "['11' '26' '34']"], ['10', "['33']"]]

但是我不知道下一步该怎么做...

评论
  • adicta
    adicta 回复

    这是一种方法。

    例如:

    x = ["0: ['17' '19']", "1: ['32' '35']", "2: ['29']", "3: ['16']", "4: ['24' '18' '9']", "6: ['24' '26']", "9: ['11' '26' '34']", "10: ['33']"]
    res = []
    for i in x:
        m, n = i.split(": ")
        res.append([m, [int(j.strip("'")) for j in n.strip("[]").split()]])
    
    print(res[0][1][1]) #-->19
    

    或使用numpy

    import numpy as np
    
    res = []
    for i in x:
        m, n = i.split(": ")
        res.append([m, np.fromstring(n[1:-1].replace("'", ""),sep=' ').astype(int)])
    
    print(res[0][1][1])