Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What are the examples of using Python

Shulou Source: shulou.com Published: 2022-06-01 22:13:13 10月03日 Update

This article mainly explains "what are the examples of using Python". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and go deep into it slowly to study and learn "what are the examples of using Python" together!

Python object to JSON object

import json

# a Python object (dict):

python_obj = {

"name": "David",

"class":"I",

"age": 6

}

print(type(python_obj))

Use the json.dumps method to convert to json objects:

# convert into JSON:

j_data = json.dumps(python_obj)

# result is a JSON string:

print(j_data) Format to json

If the dictionary is converted into a json object, ensure that the keys are in order and indented by 4 cells, how to do it?

json.dumps(j_str, sort_keys=True, indent=4)

Examples:

import json

j_str = {'4': 5, '6': 7, '1': 3, '2': 4}

print(json.dumps(j_str, sort_keys=True, indent=4)) Find the top 3 largest or smallest numbers in the list

Use the nlargest method in heapq:

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)

Find the minimum number of 3 corresponding to this, using the nsmallest method in heapq:

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) Use heap sort list in ascending order

Using heapq module, first build heap on list, default to small root heap, call len(nums) secondary 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)

Thank you for reading, the above is the content of "what are the examples of using Python", after learning this article, I believe that everyone has a deeper understanding of what problems there are in using Python examples, and the specific use needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Examples objects methods modules learning minimum content maximum order number ascending order dictionary that is ideas situations articles more formats knowledge knowledge points Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Apple Shulou Tech Info vpn Microsoft