0

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

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.