【问题标题】:Python while loop to search for highest value in filePython while循环搜索文件中的最大值
【发布时间】:2017-02-21 05:14:05
【问题描述】:

我正在编写一个循环来搜索一个 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

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

【问题讨论】:

  • 有什么帮助是您的输入样本...
  • 需要将字符串转换为数字:check = int(newline[-1])
  • 我会尝试在此处添加一行,我将不得不看看它的格式。 edit 看起来很糟糕我不确定它是否有帮助7675 STANDARD WESTWOOD NJ PRIMARY 40.98 -74.03 NA-US-NJ-WESTWOOD FALSE 13245 24083 1089095041
  • 所以我放弃了在评论中发帖的尝试,并在我的数据中添加了一个谷歌表格链接,不确定这是否有帮助

标签: python loops max


【解决方案1】:

您可以使用不同的方法解决此问题。

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,不知道我能做到这一点,谢谢你的建议!
猜你喜欢
  • 2015-07-07
  • 2020-03-19
  • 1970-01-01
  • 2016-05-25
  • 2014-11-02
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
相关资源
最近更新 更多