繁体   English   中英

如何根据案例数量分隔输入文件?

[英]How can I seperate the input file according to the number of cases?

我在 Python 中有一个编程问题,我根据输入文件回答。 在这个测试文件中:

2
5
0.0
25.0
50.0
75.0
100.0
6
12.3
-67.1
122.8
428.4
-15.9
221.0

第一行“2”表示此文件中存在的案例数。 我们还有 '5' 和 '6',它们代表案例中的浮点数。 如何根据案例数量拆分文件?

就像我在评论中说的那样,你不需要 2、5 和 6 我建议如果你控制数据只是有浮点数并使用新行来分隔它们,但itertools.groupby仍然可以在这里使用,只是确定是否行中有一个句点,你有你的花车。

from itertools import groupby 
with open('filename.txt') as f:
    all_floats = [list(map(float, g)) for  k, g in groupby(f, lambda s: '.' in s) if k]
    no_of_cases = len(all_floats)
    case_lens = list(map(len, all_cases))

考虑到输入位于名为input.txt的文件中,您可以使用类似这样的内容单独读取浮点数

with open('input.txt', 'r') as f:
no_of_test_cases = int(f.readline().strip())
i = 0
while i < no_of_test_cases:
    no_of_floats = int(f.readline().strip())
    floats = []
    for _ in range(no_of_floats):
        floats.append(float(f.readline().strip()))
    print(floats)
    # Do your calculations/operations
    i += 1

这使

[0.0, 25.0, 50.0, 75.0, 100.0]
[12.3, -67.1, 122.8, 428.4, -15.9, 221.0]

暂无
暂无

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

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