In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the "what Python tips", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "what Python tips" bar!
Set
Developers often forget that Python also has collection data types, and everyone likes to use lists to handle everything.
What is a set? To put it simply: a set is a collection of disordered things that do not contain repetitive elements.
If you are proficient in sets and their logic, then many problems can be easily solved. For example, how do you get the letters that appear in a word?
Myword = "NanananaBatman" set (myword) {'n','m','n','B','a','t'}
It's that simple, problem solved, and this example comes from the official documentation of Python, so don't be too surprised.
To give another example, how do you get the elements of a list without repeating it?
# first you can easily change set to list and other way around mylist = ["a", "b", "c", "c"] # let's make a set out of it myset = set (mylist) # myset will be: {'a', 'baked,' c'} # and, it's already iterable so you can do: for element in myset: print (element) # but you can also convert it to list again: mynewlist = list (myset) # and mynewlist will be: ['a'' 'baked,'c']
We can see that the "c" element is no longer repeated. There is only one thing you need to note that the order of elements between mylist and mynewlist may be different:
Mylist = ["c", "c", "a", "b"] mynewlist = list (set (mylist)) # mynewlist is: ['a', 'baked,' c']
As you can see, the order of the elements in the two lists is different.
Next, let's go further.
Suppose there is an one-to-many relationship between some entities, for a more specific example: users and permissions. Typically, a user can have multiple permissions. Now suppose someone wants to modify multiple permissions, that is, to add and remove certain permissions at the same time, how should this problem be solved?
# this is the set of permissions before change; original_permission_set = {"is_admin", "can_post_entry", "can_edit_entry", "can_view_settings"} # this is new set of permissions New_permission_set = {"can_edit_settings", "is_member", "can_view_entry", "can_edit_entry"} # now permissions to add will be: new_permission_set.difference (original_permission_set) # which will result: {'can_edit_settings',' can_view_entry', 'is_member'} # As you can see can_edit_entry is in both sets So we do notneed # to worry about handling it # now permissions to remove will be: original_permission_set.difference (new_permission_set) # which will result: {'is_admin',' can_view_settings', 'can_post_entry'} # and basically it's also true; we switched admin to member, andadd # more permission on settings; and removed the post_entrypermission
In general, don't be afraid to use collections, they can help you solve a lot of problems. For more details, please refer to the Python official documentation.
calendar
When developing date-and time-related features, some information can be very important, such as how many days there are in this month of a year. This question seems simple, but I believe that date and time is a very difficult topic, and I think the implementation of the calendar is a lot of problems, it is a nightmare, because you need to consider a lot of extreme situations.
So how on earth can we find out how many days there are in a month?
Import calendar calendar.monthrange (2020, 12) # will result: (1,31) # BUT! You need to be careful here, why? Let's read thedocumentation: help (calendar.monthrange) # Help on function monthrange in module calendar: # monthrange (year, month) # Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for # year, month. # As you can see the first value returned in tuple is a weekday, # not the number of the first day for a given month Let's try # to get the same for 2021 calendar.monthrange (2021, 12) (2,31) # So this basically means that the first day of December 2021 isWed # and the last day of December 2021 is 31 (which is obvious,cause # December always has 31 days) # let's play with February calendar.monthrange (2021, 2) (0,28) calendar.monthrange (2022, 2) (1,28) calendar.monthrange (2023, 2) (2,28) calendar.monthrange (2024, 2) (3 29) calendar.monthrange (2025, 2) (5,28) # as you can see it handled nicely the leap year
Of course, the first day of a month is very simple, which is the 1st. But, "the first day of a month is a week X", how to use this information? You can easily find out what day it is on a certain day:
Calendar.monthrange (2024, 2) (3,29) # means that February 2024 starts on Thursday # let's define simple helper: weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] # now we can do something like: weekdays [3] # will result in: 'Thursday' # now simple math to tell what day is 15th of February 2020: offset = 3 # it's thefirst value from monthrange for day in range (1) 29): print (day,weekdays [(day + offset-1)% 7]) 1 Thursday 2 Friday 3 Saturday 4 Sunday... 18 Sunday 19 Monday 20 Tuesday 21 Wednesday 22 Thursday 23 Friday 24 Saturday... 28 Wednesday 29 Thursday # which basically makes sense
Maybe this code is not suitable for direct production, because you can use datetime to find the week more easily:
From datetime import datetime mydate = datetime (2024, 2, 15) datetime.weekday (mydate) # will result: 3 # or: datetime.strftime (mydate, "% A") 'Thursday'
In general, there are many interesting things about the calendar module that are worth learning:
# checking if year isleap: calendar.isleap (2021) # False calendar.isleap (2024) # True # or checking how many days will be leapdays for given yearspan: calendar.leapdays (2021, 2026) # 1 calendar.leapdays (2020, 2026) # 2 # read the help here, as range is: [y1, y2), meaning that second # year is not included; calendar.leapdays (2020, 2024) # 1
Enumeration has a second parameter
Yes, enumerations have a second parameter, which may not be known to many experienced developers. Let's look at an example:
Mylist = ['await,' baked, 'dashed,' caged, 'galled,' e'] for I, item in enumerate (mylist): print (I, item) # Will give: 0 a 1 b 2 d 3 c 4 g 5 e # but, you can add a start for enumeration: for I, item in enumerate (mylist, 16): print (I, item) # and now you will get: 16 a 17 b 18 d 19 c 20 g 21 e
The second parameter specifies where the enumeration begins, such as enumerate (mylist,16) in the above code. If you need to deal with the offset, you can consider this parameter.
If-else logic
You often need to deal with different logic according to different conditions, and inexperienced developers may write code similar to the following:
OPEN = 1 IN_PROGRESS = 2 CLOSED = 3 def handle_open_status (): print ('Handling openstatus') def handle_in_progress_status (): print (' Handling inprogress status') def handle_closed_status (): print ('Handling closedstatus') def handle_status_change (status): if status = = OPEN: handle_open_status () elif status = = IN_PROGRESS: handle_in _ progress_status () elif status = = CLOSED: handle_closed_status () handle_status_change (1) # Handling open status handle_status_change (2) # Handling in progress status handle_status_change (3) # Handling closed status
Although this code doesn't look so bad, what if there are more than 20 conditions?
So, how should we deal with it?
From enum import IntEnum class StatusE (IntEnum): OPEN = 1 IN_PROGRESS = 2 CLOSED = 3 def handle_open_status (): print ('Handling openstatus') def handle_in_progress_status (): print (' Handling inprogress status') def handle_closed_status (): print ('Handling closedstatus') handlers = {StatusE.OPEN.value:handle_open_status, StatusE.IN_PROGRESS.value: handle_in_progress_status StatusE.CLOSED.value:handle_closed_status} def handle_status_change (status): if status not inhandlers: raiseException (f'No handler found for status: {status}') handler = handlers [status] handler () handle_status_change (StatusE.OPEN.value) # Handling open status handle_status_change (StatusE.IN_PROGRESS.value) # Handling in progress status handle_status_change (StatusE.CLOSED.value) # Handling closed status handle_status_change (4) # Will raise the exception
This pattern is common in Python, and it can make the code look cleaner, especially when the method is very large and needs to deal with a lot of conditions.
Enum module
The enum module provides a series of utility functions for handling enumerations, the most interesting of which are Enum and IntEnum. Let's look at an example:
From enum import Enum, IntEnum, Flag, IntFlag class MyEnum (Enum): FIRST = "first" SECOND = "second" THIRD = "third" class MyIntEnum (IntEnum): ONE = 1 TWO = 2 THREE = 3 # Now we can do things like: MyEnum.FIRST # # it has value and name attributes, which are handy: MyEnum.FIRST.value # first' MyEnum.FIRST.name # 'FIRST' # additionally we can do things like: MyEnum (' first') # Get enum by value MyEnum ['FIRST'] #, get enum by name
The code written in IntEnum is similar, but there are several differences:
MyEnum.FIRST = = "first" # False # but MyIntEnum.ONE = = 1 # True # to make first example to work: MyEnum.FIRST.value = = "first" # True
In a medium-sized code base, the enum module can be of great help in managing constants.
Localization of enum may be a bit tricky, but it can also be achieved. Let me quickly demonstrate with django: from enum import Enum from django.utils.translation import gettext_lazy as _ class MyEnum (Enum): FIRST = "first" SECOND = "second" THIRD = "third" @ classmethod def choices (cls): return [(cls.FIRST.value, _ ('first')), (cls.SECOND.value, _ (' second')) (cls.THIRD.value, _ ('third')] # And later in eg. Model definiton: some_field = models.CharField (max_length=10,choices=MyEnum.choices ())
IPython
IPython is the interactive Python, which is an interactive command-line shell, a bit like the Python interpreter.
First, you need to install iPython:
Pip install ipython
Next, you just need to replace Python with ipython when you type the command:
# you should see something like this after you start: Python 3.8.5 (default, Jul 28 2020, 12:59:40) Type 'copyright',' credits' or 'license' for more information IPython 7.18.1-- An enhanced Interactive Python. Type'?' Forhelp. In [1]:
Ipython supports many system commands, such as ls or cat,tab keys to display prompts, and you can also use the up and down keys to find previously used commands.
Thank you for your reading, these are the contents of "what Python Tips". After the study of this article, I believe you have a deeper understanding of what Python Tips are, 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.