如何在文件处理中从文本文件中找到每一行的最小值和最大值?

How to find the minimum and maximum value of the each row from the text file in file handling?

我的文件夹里有一个文本文件,文件里有很多数字的数据。我需要使用 Python 从该文件的每一行中找到最小值和最大值。结果应该是这样的:

.txt 文件中的示例数字

10  2  3  5  9 12 15
 5  9  4  8 10 98 15
23 19 89 71 56 20 11

这样的结果

[(min,max)from first row, (min,max)from second row,.........]

预期结果

[(2,15),(4,98),(11,89),.....]

我能想到的最简单的方法是 pandas。将文件读入数据帧,并将 zip 最小值和最大值一起读入。

from io import StringIO # import just for the example
import pandas as pd
s = """10  2  3  5  9 12 15
 5  9  4  8 10 98 15
23 19 89 71 56 20 11"""

# df = pd.read_csv('/path/to/file.txt', sep='\s+', header=None)
df = pd.read_csv(StringIO(s), sep='\s+', header=None)
list(zip(df.min(axis=1), df.max(axis=1)))  # -> [(2, 15), (4, 98), (11, 89)]

一个选项是读取每一行,按空格拆分,将字符串转换为整数,然后添加到列表中。然后用minmax查找相关数字:

with open('file.txt') as fil:
  results = []
  for line in fil:
    nums = [int(x) for x in line.strip().split()]
    results.append((min(nums), max(nums)))

print(results)
# [(2, 15), (4, 98), (11, 89)]

有很多方法可以做到这一点,但我首先想到的是使用 pandas 及其 read_fwf 函数(固定宽度的列)。查看您的示例 .txt 文件,数字由 2-3 个空格分隔,因此您不能使用一个特定的分隔符(除非它是 \t - 然后使用 pd.read_csv())。之后你可以:

with open("textfile.txt", 'r') as file:
    df = pd.read_fwf(file, colspecs=[widths_of_your_colums])

稍后您可以使用您描述的算法。

list = [(min(row), max(row)) for row in df]

遍历线条,拆分。转换为 int 并使用 min / max

with open ('in.txt') as f:
  data = []
  for line in f:
    numbers = [int(x) for x in line.strip().split()]
    data.append((min(numbers),max(numbers)))
print(data)

输出

[(2, 15), (4, 98), (11, 89)]
with open("file.txt", "r") as f:
    num_list = [list(map(lambda x: int(x), line.strip().split())) for line in f]
out = [(min(li), max(li)) for li in num_list]