第一个帖子,我在这里可能没有任何业务,但是这里...

如何从“for in”循环的输出中找到最大值和最小值?

我试过 min() 和 max() 并得到以下错误...

TypeError: 'int' object is not iterable

这是我的代码...
import urllib2
import json

def printResults(data):
  # Use the json module to load the string data into a dictionary
  theJSON = json.loads(data)

  # test bed for accessing the data
  for i in theJSON["features"]:
   t = i["properties"]["time"]
   print t

def main():
  # define a variable to hold the source URL
  urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"

  # Open the URL and read the data
  webUrl = urllib2.urlopen(urlData)
  #print webUrl.getcode()
  if (webUrl.getcode() == 200):
    data = webUrl.read()
    # print out our customized results
    printResults(data)
  else:
    print "Received an error from server, cannot retrieve results " +  str(webUrl.getcode())

if __name__ == "__main__":
   main()

任何指针将不胜感激!

最佳答案

您可以在可迭代对象上使用 minmax。由于您正在循环 theJSON["features"] ,您可以使用:

print min(e["properties"]["time"] for e in theJSON["features"])
print max(e["properties"]["time"] for e in theJSON["features"])

您还可以将结果存储在变量中,以便以后使用:
my_min = min(...)
my_max = max(...)

正如@Sabyasachi 评论的那样,您还可以使用:
print min(theJSON["features"], key = lambda x:x["properties"]["time"])

关于python - 从 'for in' 循环中获取最小值和最大值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22203740/

10-11 20:13
查看更多