Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python for beginners

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how beginners use Python". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use Python for beginners.

1. When using a list

Lists allow you to store elements of various data types without limiting their size, and although this flexibility makes the list the first choice for collecting data, there are actually some best practice scenarios for using and not using it.

Lists should be used when storing elements of the same nature (data type and meaning). Python does not limit this programmatically, and storing a single natural item in a list makes the developer's job easier. It is easy for developers to predict what items will be on the list in the future and write scripts with confidence.

Think about the list of items below. The list does not contain items of a single nature, and the developer cannot determine whether the list contains house parts, dimensions, or other things, so he should deal with different projects separately:

List_of_things = ['Door', 2, True, [2.3,1.4])]

Think about the list of fruits and scores below. In the first two items, you can easily infer that the first list will always contain the fruit name, while the second list will always contain the score value:

List_of_fruits = ['apple','orange',' pear', 'cherry',' banana'] list_of_scores = [80,98,50,55,100]

Tuples are more appropriate when storing items with different meanings or data types. Tuples do not provide the flexibility to store unrestricted items without creating new objects (because tuples are immutable).

two。 When iterating over a connection string

In Python, everything is an object, both mutable and immutable. Whenever you update the value assigned to an object, an immutable object needs to create a new object, while a mutable object does not.

Suppose you want to generate the entire alphabet in one string. Because a string is an immutable object, you get a new object whenever you concatenate a string value with the "+" operator.

One_line_alphabet =''for letter_index in range (ord (' a'), ord ('z')): one_line_alphabet + = chr (letter_index)

The Join function is the preferred method for concatenating strings. The calculation time can be reduced by about 3 times by using the join function. In one test I did, it took 0.135 seconds to iteratively concatenate 1 million string values and only 0.044 seconds to use the join () function.

Small_letters = [chr (I) for i inrange (ord ('a'), ord ('z') + 1)] single_line_alphabet = '.join (small_letters)

Therefore, use the join function when you need to connect to a list of strings. If you use the join function to concatenate several strings, you will not feel the performance difference intuitively. To concatenate several string values, use .format instead of the "+" operator. For example:

Name= 'John' surname=' Doe' full_name ='{name} {surname} '.format (namename=name, surnamesurname=surname)

3. When reading and writing files

To read and write a file using Python, you first need to open the file with the built-in open function. Open the file, read or write the contents, and close the file. Some problems may occur during the operation, such as forgetting to close the file and exception handling failure.

After the operation is complete, forgetting to close the file will cause subsequent problems. For example, if you forget to close the file after writing it, the write operation will not be saved to the file, and you will retain the resources allocated on the computer while the file remains open. If exceptions and errors are not handled manually when working with the file, the file remains open.

F = open (file='file.txt', mode='r') lines = f.readlines ()... F.close ()

It is recommended that you use the with keyword when opening a file. With is a context manager that encapsulates code and ensures that exceptions are handled automatically. For example, when you read and write a file, any faults that may occur in with-body can automatically handle exceptions and always keep the file closed.

With open ('file.txt') as f: read_data = f.read ()...

If you skip with, you need to handle everything yourself, closing files and exception handling. With will make your life easier and keep things under control.

4. When skipping the generator

In many scenarios, you need to generate a list of values that will be used later in the script. For example, you need to generate a combination of all three numbers for the first 100 numbers.

Combinations = [] value = 100for i in range (value): for j in range (value): for k in range (value): combinations.append ((I, jjinger k))

When the executed command is complete, the list combination will contain 1m tuples, each with three integer values. These values are kept in memory until they are deleted. Use the getobjectsize function in the sys module to check the size of the object and the result is 8.29MB.

Instead of using lists to store values and save them all to memory, you can create a generator that generates a combination every time you use it. This reduces memory consumption and improves running speed.

Defgenerate_combinations_of_three (value): for i in range (value): for j in range (value): for k in range (value): yield (I, j, k) gen = generate_combinations_of_three (100) next (gen) # yields (0,0,0) next (gen) # yileds (0,0,1).

So, use generators as much as possible. Always keep in mind that memory capacity is limited and optimize memory usage as much as possible. Use generators, especially when developing scalable solutions.

5. When using the push type

There are programmers who follow the guidelines of Python The Zen of Python when writing code in Python. If you are new to using Python, you may tend to exaggerate some of the ideas of Python Zen and avoid the important points in others.

This is the easiest thing to notice when you get to know the deduction-you tend to translate the "every" loop in the deduction. Suppose you have a three-dimensional digital matrix, you will probably want to planarize it.

Matrix = [1,2,3], [4,5,6], [7,8,9]], [[10,20,30], [40,50,60], [70,80,90]

Using list derivation, the planarization process is as follows:

Flatten_list = [x for sub_matrix inmatrix for row in sub_matrix for x in row]

Using loops, the flattening process is as follows:

Flatten_list = [] for sub_matrix in matrix: for row in sub_matrix: for x in row: flatten_list.append (x) Thank you for reading, the above is the content of "how beginners use Python". After the study of this article, I believe you have a deeper understanding of how beginners use Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report