简体   繁体   English

读取文本或 CSV 文件并分成以空格分隔的组

[英]Read text or CSV file and break into groups separated by space

I have a .csv file with data as:我有一个.csv文件,其中的数据为:

20
40
25

50
60
80

10
25
34
75
50

50
60

I need to read this file and create groups of numbers whenever a blank value is found.每当发现空白值时,我都需要读取此文件并创建数字组。 Hence, for the example above, it should become:因此,对于上面的例子,它应该变成:

final_list = [
    [20, 40, 25],
    [50, 60, 80],
    [10, 25, 34, 75, 50],
    [50, 60]
]

Just read a csv file line by by line & than one blank string in the list, you can use itertools.groupby like this:只需逐行读取一个 csv 文件,而不是列表中的一个空白字符串,您可以像这样使用itertools.groupby

from itertools import groupby
with open(r"codeMaster.csv") as fp:
    line = fp.readlines()

line = [i.strip() for i in line]

print([list(g) for k, g in groupby(line, key=bool) if k])

Gives #给#

[['20', '40', '25'], ['50', '60', '80'], ['10', '25', '34', '75', '50'], ['50', '60']]

More pythonic ##更多 pythonic ##

with open(r"CodeMaster.csv") as fp:
    line = fp.readlines()

line = [i.strip() for i in line]
result = [[]]
for i in line:
    if not i:
        result.append([])
    else:
        result[-1].append(i)
print(result)

Also Gives #还给#

[['20', '40', '25'], ['50', '60', '80'], ['10', '25', '34', '75', '50'], ['50', '60']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM