[英]list with string values to 2D array
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...但我不知道下一步该怎么做...
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或使用 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])
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 eg ['1', '32', '35']
.简单的正则表达式
\d+
将您要查找的列表条目中的所有数字提取为列表,例如['1', '32', '35']
。 Then we map
these to integers and unpack it to the index and the remaining values eg idx = 1
and vals = [32, 35]
.然后我们
map
为整数并将其解压缩到索引和剩余值,例如idx = 1
和vals = [32, 35]
。 Then store for further use.然后储存以备后用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.