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

时间:2014-03-05 16:39:21

标签: 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()

任何指针都将非常感谢!

3 个答案:

答案 0 :(得分:2)

您可以在iterables上使用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"])

答案 1 :(得分:1)

以下是如何手动跟踪最小值和最大值的示例。

minVal = 0
maxVal = 0
for i in yourJsonThingy:
    if i < minVal:
        minVal = i
    if i > maxVal:
        maxVal = i

你不能这样做:

for i in yourJsonThingy:
    maxVal = max(i)

因为我只是一个整数而且没有最大值

但您可以在整体列表中执行这些操作

maxVal = max(yourJsonThingy)
minVal = min(yourJsonThingy)

答案 2 :(得分:1)

如果你只想通过你的迭代一次,(说这是一项昂贵的操作,而且这是你应该做的唯一原因,而不是max或{{1}分开,但是说,以下是单独调用两者的性能改进,见下面的数字):

min

用法:

def max_min(iterable, key=None):
    ''' 
    returns a tuple of the max, min of iterable, optional function key 
    tuple items are None if iterable is of length 0
    '''
    it = iter(iterable)
    _max = _min = next(it, None)
    if key is None:
        for i in it:
            if i > _max:
                _max = i
            elif i < _min:
                _min = i
    else:
        _max_key = _min_key = key(_max)
        for i in it:
            key_i = key(i)
            if key_i > _max_key:
                _max, _max_key = i, key_i
            elif key_i < _min_key:
                _min, _min_key = i, key_i
    return _max, _min

进行表现检查:

>>> max_min(range(100))
(99, 0)
>>> max_min(range(100), key=lambda x: -x)
(0, 99)

对于同时调用内置函数>>> timeit.timeit('max(range(1000)), min(range(1000))', setup=setup) 70.95577674100059 >>> timeit.timeit('max_min(range(1000))', setup=setup) 65.00369232000958 max而没有lambda的情况,这大约提高了9%。用lambda:

min

使用lambdas单独调用每个语句可以提高40%以上。

相关问题