读取行和处理数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读取行和处理数据相关的知识,希望对你有一定的参考价值。

我有这样一段代码,用于将文本文件的多行读入数组,然后将str值改为int,再将int打印出来。

文本文件的值是由4个数字组成的行,中间用空格分隔。

例如

1 2 3 4
3 6 8 5
3 8 1 7 
3 6 7 8 
3 5 6 8
    with open('file2.txt') as f:
        data = [f.readline().rstrip().split(' ') for x in range(4)]

    # print(data)

    array1, array2, array3, array4 = data

    count = 1

    for i in array1:
val = int(i)
# print(val)

if count == 1:
    val1 = val
elif count == 2:
    val2 = val
elif count == 3:
    val3 = val
elif count == 4:
    val4 = val
count += 1

    count = 1

    for i in array2:
        val = int(i)
        # print(val)

        if count == 1:
            val5 = val
        elif count == 2:
            val6 = val
        elif count == 3:
            val7 = val
        elif count == 4:
            val8 = val
        count += 1

    for i in array3:
val = int(i)
# print(val)

if count == 1:
    val9 = val
elif count == 2:
    val10 = val
elif count == 3:
    val11 = val
elif count == 4:
    val12 = val
count += 1

    for i in array4:
val = int(i)
# print(val)

if count == 1:
    val13 = val
elif count == 2:
    val14 = val
elif count == 3:
    val15 = val
elif count == 4:
    val16 = val
count += 1

    print(val1, val2, val3, val4)
    print(val5, val6, val7, val8)
    print(val9,val10,val11,val12)
    print(val13,val14,val15,val16)
答案

从你读取文件的方式开始,你可以用这样的方式。

with open('file2.txt') as f:
    data = [f.readline().rstrip().split(' ') for x in range(5)]

data = [[int(x) for x in i] for i in data]

for each in data:
  print(*each)

输出:

1 2 3 4
3 6 8 5
3 8 1 7
3 6 7 8
3 5 6 8

或者..:

with open('file2.txt') as f:
    data = [f.readline().rstrip().split(' ') for x in range(5)]

for each in list(map(int,i) for i in data):
  print(*each)

以上是关于读取行和处理数据的主要内容,如果未能解决你的问题,请参考以下文章

java读取txt文件,显示换行和空格,求教!

Xargs

从C中的文件中读取行和列

java如何高效读取文本的第N行和最后N行?

非常快的文本文件处理 (C++)

linux基础命令:xargs