Whether it is python development or the development of any other language, if we can master some useful tips and techniques during development, it will definitely greatly improve our development efficiency. Today, the editor and everyone What I’m sharing is some common mistakes that beginners often make when learning the language in Python development. Let’s take a look.
">
Please note: This article assumes that we are all using Python 3
1. List comprehension
You have a list: bag = [1, 2, 3, 4, 5]
Now you want to double all the elements so that it looks like this: [2, 4, 6 , 8, 10]
Most beginners will probably do it like this based on their previous language experience
bag?=?[1,?2,?3,?4,?5]? for?i?in?range(len(bag)):? ?bag[i]?=?bag[i]?*?2
But there is a better way:
bag?=?[elem?*?2?for?elem?in?bag]
It’s very simple, right? ? This is called Python's list comprehension.
2. Traverse the list
Continue, or avoid doing this if possible:
bag?=?[1,?2,?3,?4,?5]? for?i?in?range(len(bag)):? ?print(bag[i])
Instead it should be like this:
bag?=?[1,?2,?3,?4,?5]? for?i?in?bag:? ?print(i)
If x is a list, you can iterate over its elements. In most cases you don't need the index of each element, but if you must, then Just use the enumerate
function. It looks like the following: bag?=?[1,?2,?3,?4,?5]?
for?index,?element?in?enumerate(bag):?
?print(index,?element)
It’s very intuitive and clear. 3. Element exchange
If you are from java. Or
C languageIf you switch to Python, you may be used to this:
a?=?5? b?=?10 #?交換?a?和?b tmp?=?a? a?=?b? b?=?tmp
But Python provides a more natural and better method! a?=?5?
b?=?10?
#?交換a?和?b
a,?b?=?b,?a
Pretty enough, right?
4. Initialization list
If you want a list of 10
integers0, you may first think of:
bag?=?[]? for?_?in?range(10):? ?bag.append(0)
Let’s try another way: bag?=?[0]?*?10
Look, how elegant
Note: If your list contains a list, doing this will produce a shallow copy:
bag_of_bags?=?[[0]]?*?5?#?[[0],?[0],?[0],?[0],?[0]]? bag_of_bags[0][0]?=?1?#?[[1],?[1],?[1],?[1],?[1]]
Oops! All lists have changed, and we just want to change the first one:
bag_of_bags?=?[[0]?for?_?in?range(5)]? #?[[0],?[0],?[0],?[0],?[0]] bag_of_bags[0][0]?=?1? #?[[1],?[0],?[0],?[0],?[0]]
Also remember:
" Premature optimization is the root of all evil"
Ask yourself, is it necessary to initialize a list?5. ConstructString
You will often need to Print strings. If there are manyvariables
, avoid the following:
name?=?"Raymond"? age?=?22? born_in?=?"Oakland,?CA"? string?=?"Hello?my?name?is?"?+?name?+?"and?I'm?"?+?str(age)?+?"?years?old.?I?was?born?in?"?+?born_in?+?"."? print(string)
Well, how messy does this look? You can use a nice and concise method instead, .format #. ##Do this:
name?=?"Raymond"? age?=?22? born_in?=?"Oakland,?CA"? string?=?"Hello?my?name?is?{0}?and?I'm?{1}?years?old.?I?was?born?in?{2}.".format(name,?age,?born_in)? print(string)Much better! Python allows you to return multiple elements in a function, This makes life easier, but
Common mistakes
when unpacking tuples:def?binary():? ?return?0,?1 result?=?binary()? zero?=?result[0]? one?=?result[1]This is not necessary, you can change it to this:
def?binary():? ?return?0,?1 zero,?one?=?binary()If you need all elements to be returned, use an underscore_:
zero,?_?=?binary()It’s so efficient!
7. Access Dicts (dictionaries)
You will also often writekey
, pair (key, value) to dicts. If you try to access a key that does not exist in the dict, you may be tempted to do this to avoid KeyError errors:countr?=?{}? bag?=?[2,?3,?1,?2,?5,?6,?7,?9,?2,?7]? for?i?in?bag:? ?if?i?in?countr: ??countr[i]?+=?1 ?else: ??countr[i]?=?1 for?i?in?range(10):? ?if?i?in?countr: ??print("Count?of?{}:?{}".format(i,?countr[i])) ?else: ??print("Count?of?{}:?{}".format(i,?0))However, it is better to use get() Method.
countr?=?{}? bag?=?[2,?3,?1,?2,?5,?6,?7,?9,?2,?7]? for?i?in?bag:? ?countr[i]?=?countr.get(i,?0)?+?1 for?i?in?range(10):? ?print("Count?of?{}:?{}".format(i,?countr.get(i,?0)))Of course you can also use setdefault instead.
This is a simpler but more expensive method:
bag?=?[2,?3,?1,?2,?5,?6,?7,?9,?2,?7]? countr?=?dict([(num,?bag.count(num))?for?num?in?bag]) for?i?in?range(10):? ?print("Count?of?{}:?{}".format(i,?countr.get(i,?0)))You can also use dict derivation.
countr?=?{num:?bag.count(num)?for?num?in?bag}These two methods are expensive because they traverse the list every time count is called. 8 Using libraries Just import existing libraries and you can do what you really want. Still talking about the previous example, we build a function to count the number of times a number appears in the list. Well, there is already a library that can do such a thing.
from?collections?import?Counter? bag?=?[2,?3,?1,?2,?5,?6,?7,?9,?2,?7]? countr?=?Counter(bag) for?i?in?range(10):? ?print("Count?of?{}:?{}".format(i,?countr[i]))Some reasons for using the library: 1. The code is correct and tested. 2. Their algorithm may be optimal, so it can run faster. 3. Abstraction: They are clearly pointed and documented, and you can focus on those that have not yet been implemented. 4. In the end, it’s already there, you don’t have to reinvent the wheel. 9. Slicing/stepping in the listYou can specify the start point and stop point, like this list[start:stop:step]. We take out the first 5 elements in the list:
bag?=?[0,?1,?2,?3,?4,?5,?6,?7,?8,?9]? for?elem?in?bag[:5]:? ?print(elem)This is slicing, we specify the stop point is 5, and 5 elements will be taken out from the list before stopping. What to do if it is the last 5 elements?
bag?=?[0,?1,?2,?3,?4,?5,?6,?7,?8,?9]? for?elem?in?bag[-5:]:? ?print(elem)Don’t you understand? -5 means take 5 elements from the end of the list. If you wanted to operate on intervals in the list, you might do this:
bag?=?[0,?1,?2,?3,?4,?5,?6,?7,?8,?9]? for?index,?elem?in?enumerate(bag):? ?if?index?%?2?==?0: ??print(elem)But you should do it like this:
bag?=?[0,?1,?2,?3,?4,?5,?6,?7,?8,?9]? for?elem?in?bag[::2]:? ?print(elem) #?或者用?ranges bag?=?list(range(0,10,2))? print(bag)This is the step in the list . list[::2] means traversing the list and taking out an element in two steps. You can use list[::-1] to do a cool flipping list. 10. Tab key or space key
In the long run, mixing tabs and spaces will cause disaster, and you will see IndentationError: unexpected indent. Whether you choose the tab key or the space bar, you should keep using it throughout your files and projects.
One reason to use spaces instead of tabs is that tabs are not the same in all editors. Depending on the editor used, tabs may be treated as 2 to 8 spaces.
You can also use spaces to define tabs when writing code. This way you can choose how many spaces to use as tabs. Most Python users use 4 spaces.
Summary
The above are the tips that you should pay attention to in Python development. I hope it will be helpful to everyone in learning and using python. If you have any questions, you can leave a message to communicate.
The above is the detailed content of Share ten things to note when developing Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, you need to use the nonlocal keyword; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

Add timeout control to Python's for loop. 1. You can record the start time with the time module, and judge whether it is timed out in each iteration and use break to jump out of the loop; 2. For polling class tasks, you can use the while loop to match time judgment, and add sleep to avoid CPU fullness; 3. Advanced methods can consider threading or signal to achieve more precise control, but the complexity is high, and it is not recommended for beginners to choose; summary key points: manual time judgment is the basic solution, while is more suitable for time-limited waiting class tasks, sleep is indispensable, and advanced methods are suitable for specific scenarios.

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

Python default parameters are evaluated and fixed values ??when the function is defined, which can cause unexpected problems. Using variable objects such as lists as default parameters will retain modifications, and it is recommended to use None instead; the default parameter scope is the environment variable when defined, and subsequent variable changes will not affect their value; avoid relying on default parameters to save state, and class encapsulation state should be used to ensure function consistency.
