我正在编写一个循环来搜索 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 行数据,但我无法集中精力获得正确的最大值。抱歉,如果有任何模糊之处,这是我在网站上提出的第一个问题和帖子。
另一个编辑添加了我正在搜索的数据,到目前为止,回复确实很有帮助
最佳答案
您可以使用不同的方法来解决这个问题。
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/