gpt4 book ai didi

python - 在文本文件中找到最大的数字并写下它的行

转载 作者:行者123 更新时间:2023-12-04 15:16:00 25 4
gpt4 key购买 nike

我有一个 txt 文件,看起来像这样:(第一行是关于列的信息,我有 150 多行)

E1,   E2,  E3,  E4,  E5,    E6,       E7,     E8
abc, cba, dfa, gds, 60371, 42.1234, -2.12, hkfka
grs, fx, hgf, eff, 30331, 124, 31313.23, gj
.
.
.

预期输出:

abc, cba, dfa, gds, 60371, 42.1234, -2.12, hkfka

我用with open方法读取这个文件,然后我想在E5的列中找到最大的数字。在本例中为“60371”。找到它之后,我想将它整行写入一个文本文件。我可以通过将字符串添加到列表中找到最大的数字,但不能用这种方法写出它。

    list = []
with open(file.csv, "r") as m:
text = m.readlines()[1:]
text = [line.replace(' ', '') for line in text]
for line in text:
currentline = line.split(",")
number= currentline[4]
list.append(number)
largest = max(list)

编辑:我不允许使用任何进口商品,例如 Pandas 等。

最佳答案

1。没有库

with open('data.csv', 'r') as f:
next(f)
lines = [line.replace(' ', '').split(',') for line in f.readlines()]
numbers = [int(line[4]) for line in lines]
index = numbers.index(max(numbers))

with open('result.csv', 'w') as f:
f.write(f'{index} ({lines[index][1]})')

输出:

0 (cba)

2。使用 pandas

import pandas as pd

df = pd.read_csv('data.csv')
row = df[df[' E5'] == df[' E5'].max()]
row.to_csv('result.csv')

输出文件:

,E1,   E2,  E3,  E4,  E5,    E6,       E7,     E8
0,abc, cba, dfa, gds,60371,42.1234,-2.12, hkfka

关于python - 在文本文件中找到最大的数字并写下它的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64317485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com