python - 根据索引拆分字符串列表
问题描述
我的数据以不太有用的方式生成,首先是几个空格,然后是索引号(在本例中为 1-12),然后是与索引关联的实际值。我想要的是将字符串拆分为两个列表:1 个包含索引的列表和 1 个包含值的列表。我编写了以下代码,适用于我想要的。但是,对于几千行的数据集,它似乎很麻烦并且需要很多秒才能运行。有没有办法加快大型数据集的速度?
data = [' 11.814772E3',
' 2-1.06152E3',
' 33.876477E1',
' 4-2.65704E3',
' 51.141537E4',
' 61.378482E4',
' 71.401565E4',
' 86.782599E3',
' 9-1.22921E3',
' 103.400054E3',
' 111.558086E3',
' 121.017818E4']
values_total = [] #without empty strings
location = [] #index when id goes to value
ids = [] #Store ids
values = [] #Store values
step_array = np.linspace(1,1E3,1E3) #needed to calculate index values
for i in range(len(data)):
#Check how many indices have to be removed
location.append([])
location[i].append(int(math.log10(step_array[i]))+1)
#Store values after empty strings
for j in range(len(data[i])):
values_total.append([])
if data[i][j] != ' ':
values_total[i].append(data[i][j])
#Split list based on calculated lengths
ids.append(values_total[i][:location[i][0]])
values.append(values_total[i][location[i][0]:])
解决方案
你可以试试下面的代码:
indices = []
vals = []
for i, d in enumerate(data, 1): # enumerate starting from 1, so we know current index
tmp = d.strip() # remove whitespace
split_idx = len(str(i)) # figure out the length of the current index
indices.append(i) # current index
vals.append(float(tmp[split_idx:])) # everything after current index length
推荐阅读
- python - Tkinter,其他类的功能
- 3d - 为什么我无法打开这个 GLTF 3D 文件?
- purescript - 是否可以将类型类约束放在(数据)类型参数上?
- javascript - 如何在Active Ionic Vue时每次在安装上调用函数?
- android - java.lang.Object 类型无法解析。它是从所需的 .class 文件 android studio 中间接引用的
- python - 访问类型。文字值
- scala - 获取Scala3宏中的类型信息
- image - 小部件中的颤振数据不显示,仅在单击后退按钮并返回小部件页面时显示
- powerbi - 如何在 PowerBI 中显示第 90 个百分位的卡片
- php - HTTP 请求重复(Jquery/PHP)