Python将行拆分为单独的列表

2024-09-27 19:09:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件中的数据,它被空间分隔成右对齐的列。我希望能够采取每一列,并把它在一个列表,基本上就像你会做一个数组。我似乎找不到一个与

left(strname,#ofcharacters)/mid(strname,firstcharacter,lastcharacter)/right(strname,#ofcharacters)

就像你通常用VB来完成任务一样。在Python中,如何分离数据并将每个类似的“unit”及其值放在下一行中。你知道吗

有可能吗?哦,是的,有些间距是12个字符间隔(右对齐),而另一些是15个字符间隔。你知道吗

-1234      56    32452      68584.4   Extra_data
-5356       9      546      12434.5   Extra_data
-  90      12     2345      43522.1   Extra_data

期望输出:

[-1234, -5356, -90]
[56, 9, 12]
[32452, 546, 2345]
etc

Tags: 数据列表data间隔空间数组leftextra
2条回答

只需在没有参数的情况下使用str.split();它会在任意宽度的空格上拆分输入字符串:

>>> '  some_value    another_column    123.45       42  \n'.split()
['some_value', 'another_column', '123.45', '42']

请注意,任何包含空格的列也将被拆分。你知道吗

如果要在中有列表,则需要转置行:

with open(filename) as inputfh:
    columns = zip(*(l.split() for l in inputfh))

在python中,您正在寻找的等效方法是str.split(),它不带任何参数来拆分空格上的字符串。它还将处理任何尾随的换行符/空格,并且在VB示例中,您不需要关心数据宽度。你知道吗

示例

with open("data.txt") as fin:
    data = map(str.split, fin) #Split each line of data on white-spaces
    data = zip(*data) #Transpose the Data

但是,如果有带空格的列,则需要根据列位置拆分数据

>>> def split_on_width(data, pos):
    if pos[-1] != len(data):
        pos = pos + (len(data), )
    indexes = zip(pos, pos[1:]) #Create an index pair with current start and
                                #end as next start
    return [data[start: end].strip() for start, end in indexes] #Slice the data using
                                                                #the indexes

>>> def trynum(n):
    try:
        return int(n)
    except ValueError:
        pass
    try:
        return float(n)
    except ValueError:
        return n


>>> pos
(0, 5, 13, 22, 36)
>>> with open("test.txt") as fin:
    data = (split_on_width(data.strip(), pos) for data in fin)
    data = [[trynum(n) for n in row] for row in  zip(*data)]       


>>> data
[[-1234, -5356, -90], [56, 9, 12], [32452, 546, 2345], [68584.4, 12434.5, 43522.1], ['Extra_data', 'Extra_data', 'Extra_data']]

相关问题 更多 >

    热门问题