查找max并从lis中提取数据

2024-10-02 18:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件与二十个汽车价格和它的序列号有50行在这个文件。我想找出每10行的最高车价及其序列号。你知道吗

你知道吗priceandserial.txt文件你知道吗

102030 4000.30
102040 5000.40
102080 5500.40
102130 4000.30
102140 5000.50
102180 6000.50
102230 2000.60
102240 4000.30
102280 6000.30
102330 9000.70
102340 1000.30
102380 3000.30
102430 4000.80
102440 5000.30
102480 7000.30

当我尝试Python的内置max函数时,得到的最大值是102480。你知道吗

x = np.loadtxt('carserial.txt', unpack=True)

print('Max:', np.max(x))  

期望结果:

102330 9000.70
102480 7000.30

文件中有50行,因此我应该有一个序列和每10行最大价格5行的结果。你知道吗


Tags: 文件函数txtnp价格汽车内置max
3条回答

恕我直言,我认为第一个解决方案设计过度了。这个任务不需要numpymath,只需要一本字典。在循环过程中,如果最新值大于当前值,则更新字典;如果不大于当前值,则不执行任何操作。在第10项中,将字典中的值附加到输出列表并重置缓冲区。你知道吗

with open('filename.txt', 'r') as opened_file:
    data = opened_file.read()

rowsplitdata = data.split('\n')
colsplitdata = [u.split(' ') for u in rowsplitdata]
x = [[int(j[0]), float(j[1])] for j in colsplitdata]

output = []
buffer = {"max":0, "index":0}
count = 0
#this assumes x is a list of lists, not a numpy array
for u in x:
    count += 1
    if u[1] > buffer["max"]:
        buffer["max"] = u[1]
        buffer["index"] = u[0]
    if count == 10:
        output.append([buffer["index"], buffer["max"]])
        buffer = {"max":0, "index":0}
        count = 0
#append the remainder of the buffer in case you didn't get to ten in the final pass
output.append([buffer["index"], buffer["max"]])
output
[[102330, 9000.7], [102480, 7000.3]]

您应该对其进行迭代,并为每10行提取最大值:

import math

# New empty list for colecting the results
max_list=[]

#iterate thorught x supposing
for i in range(math.ceil(len(x)/10)):
   ### append only 10 elments if i+10 is not superior to the lenght of the array
   if i+11<len(x):    
       max_list=max_list.append(np.max(x[i:i+11]))
   ### if it is superior, then append all the remaining elements
   else:
       max_list=max_list.append(np.max(x[i:]))

这应该是你的工作。你知道吗

number_list = [[],[]]
with open('filename.txt', 'r') as opened_file:
    for line in opened_file:
        if len(line.split()) == 0:
            continue
        else:
            a , b = line.split(" ")
            number_list[0].append(a)
            number_list[1].append(b)
col1_max, col2_max = max(number_list[0]), max(number_list[1])
col1_max, col2_max

只需更改filenamecol1_maxcol2_max具有相应列的最大值。您可以编辑代码以容纳更多列。你知道吗

相关问题 更多 >