首页 > 解决方案 > 根据索引拆分字符串列表

问题描述

我的数据以不太有用的方式生成,首先是几个空格,然后是索引号(在本例中为 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]:])

标签: python

解决方案


你可以试试下面的代码:

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

推荐阅读