Reputation: 311
A list of string values looks like this:
x = ["0: ['17' '19']", "1: ['32' '35']", "2: ['29']", "3: ['16']", "4: ['24' '18' '9']", "6: ['24' '26']", "9: ['11' '26' '34']", "10: ['33']"]
I want a 2D array so I can do this:
print(x[0][1][1])
19
First I get of rid of the colon:
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']"]]
But I don't know what to do next ...
Upvotes: 0
Views: 43
Reputation: 18315
import re
the_list = ["0: ['17' '19']", "1: ['32' '35']", "2: ['29']"]
new_list = []
for entry in the_list:
idx, *vals = map(int, re.findall(r"\d+", entry))
new_list.append([idx, vals])
print(new_list, new_list[0][1][1], sep="\n")
# [[0, [17, 19]], [1, [32, 35]], [2, [29]]]
# 19
The simple regex \d+
extracts all the numbers in an entry of the list you're looking for as a list e.g. ['1', '32', '35']
. Then we map
these to integers and unpack it to the index and the remaining values e.g idx = 1
and vals = [32, 35]
. Then store for further use.
Upvotes: 0
Reputation: 82805
This is one approach.
Ex:
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
Or using 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])
Upvotes: 1