Python while循环搜索文件中的最高值

标签 python loops max

我正在编写一个循环来搜索 Excel 文件。重点是检查读取行中的最高值。这是我到目前为止的代码

def maxwages():
   leave = false
   max = 0
   city = '' #city for later printing
   fo = open(path,'r') #open file
   while leave == false: 
      line = fo.readline() #read file
      newline = line.split(',')
      check = newline[len(newline)-1] #the value is the last element in the line
      if check > max: #if the checked value is higher than previous max
        max = newline[len(newline)-1] #assign new max value with checked value
        city = newline[2] #city name
        print max, city #seeing what's going on
      if fo is None:
        leave = true
   print city,'Has the highest wages at',max,'dollars'
      fo.close

我当前的输出是

"TotalWages"
"City"
1089095041
"WESTWOOD"
325436960
"WOODCLIFF LAKE"
401312434
"WHITEHOUSE STATION"
528315021
"WOODBRIDGE"
896273759
"WYCKOFF"
924776075
"BRONX"
97578251
"BRONX"
98754584
"AVON"
9999157
"BUZZARDS BAY"

我不确定为什么 max 的值会下降。我必须读取的文件有 42000 行数据,但我无法集中精力获得正确的最大值。抱歉,如果有任何模糊之处,这是我在网站上提出的第一个问题和帖子。

my data

另一个编辑添加了我正在搜索的数据,到目前为止,回复确实很有帮助

最佳答案

您可以使用不同的方法来解决这个问题。

with open(path, "r") as f:
    lines = f.readlines()

    # Next line will create a list of tuples. Each tuple will be (value, city), assuming value is at position -1 of your line and city at position 2
    values_cities = [(int(line.split(',')[-1]), line.split(',')[2]) for line in lines]

    max_pair = max(values_cities) # It will find the max of every tuple (the first element, which is the value)

关于Python while循环搜索文件中的最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42353800/

相关文章:

python - 查看限制偏移量分页中的所有数据

python - 抓取爬行 : error: no such option : -o

python - 如何从文件夹中一一调用csv文件并将文件分配给变量?

Python - 确定井字游戏的赢家

sorting - 有效地找到极值

python - 是否可以使用 Django 的固定装置更改现有数据?

java - 避免在java中的循环内实例化新对象

linux - 遍历目录中的文件,创建输出文件,linux

php - 使用 INNER JOIN、GROUP BY 和 Max 的 MySql 查询

Mysql 查询最小值和最大值,限制 N 分组