从'for in'循环中获取最小值和最大值
这是我第一次发帖,我可能不太适合在这里,但我还是试试...
我该怎么从一个'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 个回答
1
如果你只想遍历一次你的可迭代对象(比如说,这个操作比较耗费资源,实际上这也是你应该这样做的唯一理由,而不是分别调用 max
或 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
和 min
(不使用 lambda 函数)提高了大约 9% 的性能。使用 lambda 函数时:
>>> timeit.timeit('max(range(1000), key=lambda x: -x),min(range(1000), key=lambda x: -x)', setup=setup)
294.17539755300095
>>> timeit.timeit('max_min(range(1000), key=lambda x: -x)', setup=setup)
208.95339999899443
这样做比分别使用 lambda 函数调用每个方法提高了超过 40% 的性能。
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)
因为i只是一个整数,没有最大值。
但是你可以在一个整数列表上进行这些操作。
maxVal = max(yourJsonThingy)
minVal = min(yourJsonThingy)
2
你可以在可迭代对象上使用 min
和 max
函数。因为你正在遍历 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"])