Python 第194-196 個(gè)小例子
194 python對(duì)象轉(zhuǎn)json對(duì)象
import json
# a Python object (dict):
python_obj = {
"name": "David",
"class":"I",
"age": 6
}
print(type(python_obj))
使用json.dumps方法轉(zhuǎn)化為json對(duì)象:
# convert into JSON:
j_data = json.dumps(python_obj)
# result is a JSON string:
print(j_data)
帶格式轉(zhuǎn)為json
若字典轉(zhuǎn)化為json對(duì)象后,保證鍵有序,且縮進(jìn)4格,如何做到?
json.dumps(j_str, sort_keys=True, indent=4)
例子:
import json
j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
print(json.dumps(j_str, sort_keys=True, indent=4))
195 發(fā)現(xiàn)列表前3個(gè)最大或最小數(shù)
使用堆模塊 heapq 里的 nlargest 方法:
import heapq as hq
nums_list = [25, 35, 22, 85, 14, 65, 75, 22, 58]
# Find three largest values
largest_nums = hq.nlargest(3, nums_list)
print(largest_nums)
相應(yīng)的求最小3個(gè)數(shù),使用堆模塊 heapq 里的 nsmallest 方法:
import heapq as hq
nums_list = [25, 35, 22, 85, 14, 65, 75, 22, 58]
smallest_nums = hq.nsmallest(3, nums_list)
print("\nThree smallest numbers are:", smallest_nums)
196 使用堆排序列表為升序
使用 heapq 模塊,首先對(duì)列表建堆,默認(rèn)建立小根堆,調(diào)用len(nums) 次heappop:
import heapq as hq
nums_list = [18, 14, 10, 9, 8, 7, 9, 3, 2, 4, 1]
hq.heapify(nums_list)
s_result = [hq.heappop(nums_list) for _ in range(len(nums_list))]
print(s_result)
更多例子,請(qǐng)點(diǎn)擊閱讀原文學(xué)習(xí):

評(píng)論
圖片
表情
