python - 从 'for in' 循环中获取最小值和最大值

标签 python

第一篇文章,我可能没空在这里,但是这里...

如何从“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/

相关文章:

python - 使用 Django send_mail 方法发送邮件非常慢

python - 属性错误 : 'module' object has no attribute 'choice'

python - scikit-learn中SGDClassifier的正则化参数和迭代

python - Airflow -BashOperator : Getting "Dag runs are deadlocked for DAG:.." error

python - 生成复制任意分布的随机数

jquery - 抓取使用ajax的网页

Python matplotlib/pylab - 3D 地毯图

python - 如果它是通过 query_property 创建的,是否可以缩小 SQLAlchemy 中生成的查询的范围?

python - Django——根据模型字段生成excel报表

python - 如何将字典列表保存到文件中?