python:findimg文件第一列中的最大数字,并考虑不同列中同一行中的其他数字
我有一个非常长的文件,大约2*10^5行乘以5列,其中填充了数字和浮动 我必须在第一列的数目中找到最大值,然后在同一行上的其他四列上考虑相应的数字。< /P> 我想我可以使用字典:键是第一列中的数字,值是包含其他值的列表。我在键中找到最大值并读取相应的值 有更聪明的方法吗?那本字典将会非常大python:findimg文件第一列中的最大数字,并考虑不同列中同一行中的其他数字,python,file,dictionary,max,Python,File,Dictionary,Max,我有一个非常长的文件,大约2*10^5行乘以5列,其中填充了数字和浮动 我必须在第一列的数目中找到最大值,然后在同一行上的其他四列上考虑相应的数字。< /P> 我想我可以使用字典:键是第一列中的数字,值是包含其他值的列表。我在键中找到最大值并读取相应的值 有更聪明的方法吗?那本字典将会非常大 一、 差点忘了:我使用的是python 2.6。每个输入文件都要重复多少次?如果是一次,为什么不直接扫描文件,保留最好的一行呢?我只需要重复一次。这听起来像是我在使用csv文件时遇到的情况,然后我用它来开发
一、 差点忘了:我使用的是python 2.6。每个输入文件都要重复多少次?如果是一次,为什么不直接扫描文件,保留最好的一行呢?我只需要重复一次。这听起来像是我在使用csv文件时遇到的情况,然后我用它来开发完整的numpy统计数据。如果您只需要将该行标识为已读,并且可以放弃其余数据,那么它只需要一次运行。
maxn=-float('inf')
with open(fname) as f:
for line in f:
if maxn<int(line.split(',')[0]):
theLine=line
#do something with that line:
print theLine
# define a sorting function based on the first numer, assuimg columns are
# separated by space or tab
f = lambda line: float(line.split()[0])
# opened file in Python is an iterator, so could be served to max() directly
with open('your_input_file') as inf:
line_with_max_num = max(inf, key=f)
# turn the other four numbers into a list and print them to the screen
# or do whatever you like with them
print [float(_) for _ in line_with_max_num.split()[1:]]
INPUT = "myfile.txt"
DELIM = ","
def first_float(s):
first = s.split(DELIM, 1)[0]
return float(first)
with open(INPUT) as inf:
max_line = max(inf, key=first_float)
max_data = [float(f) for f in max_line.split(DELIM)]