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

What are the excellent skills of Python

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "what are the excellent skills of Python". In daily operation, I believe many people have doubts about the excellent skills of Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what are the excellent skills of Python?" Next, please follow the editor to study!

1. Use Python3

Warm reminder: it has been officially announced that Python2 will no longer be supported from January 1, 2020. Most of the examples in this guide also apply only to Python3. If you are still using Python2.7, update it quickly. If you are using an Apple computer, you can easily upgrade using Homebrew.

two。 Check the minimum required version of Python

You can view the Python version directly using the code to ensure that there is no incompatibility between the script and the Python version in the future. Take a look at the example:

Ifnot sys.version_info > (2,7): # berate your user for running a 10 year # python version elifnot sys.version_info > = (3,5): # Kindly tell your user (s) he needs to upgrade # because you're using 3.5 features

Viewrawcheck_python_version.py hosted with ❤ by GitHub

3. Use IPython

Screenshot of the author

In fact, IPython is an enhanced shell. Autocomplete is amazing enough, but it has more. I like the built-in magic commands very much. Here are some examples:

% cd-used to change the current working directory

Edit-Open the editor and execute the code you typed after closing the editor

% env-shows the current environment variable

% pip install [pkgs]-install the package in an interactive environment

% time and% timeit-calculate the execution time of the Python code

Another useful feature is to reference the output of the previous command. In and Out are actual objects. You can output the third command by using Out [3].

Download the Python command to install Ipython:

Pip3install ipython

4. List derivation

List derivation can replace the ugly for loop used to populate the list. The basic syntax of list derivation is:

[expression for item in list if conditional]

This is the most basic example of populating a list with a sequence of numbers:

Mylist = [i for i inrange (10)] print (mylist) # [0,1,2,3,4,5,6,7,8,9]

Viewrawlist_comprehensions_1.py hostedwith ❤ by GitHub

At the same time, you can also use this expression for mathematical operations:

Squares = [x**2for x inrange (10)] print (squares) # [0,1,4,9,16,25,36,49, 64,81]

Viewrawlist_comprehensions_2.py hostedwith ❤ by GitHub

Even create a new function:

Defsome_function (a): return (a + 5) / 2 my_formula = [some_function (I) for i inrange (10)] print (my_formula) # [2,3,3,4,4,5,5,6,6,7]

Viewrawlist_comprehensions_3.py hostedwith ❤ by GitHub

Finally, you can use "if" to filter the list. In this example, only values that are divisible by 2 are retained.

Filtered = [i for i inrange (20) if I% 2cm 0] print (filtered) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Viewrawlist_comprehensions_4.py hosted with ❤ by GitHub

5. Check the memory usage of an object

Using sys.getsizeof (), you can check the memory of an object:

Import sys mylist = range (0, 10000) print (sys.getsizeof (mylist)) # 48

Viewrawcheck_memory_usage_1.py hostedwith ❤ by GitHub

Why does such a huge list take up only 48 bytes of memory? This is because the class returned by the range function only appears as a list. Ranges save more memory than using actual numeric lists. You can use list derivation to create a list of actual numbers in the same range:

Import sys myreallist = [x for x inrange (0, 10000)] print (sys.getsizeof (myreallist)) # 87632

Viewrawcheck_memory_usage_2.py hosted with ❤ by GitHub

6. Return multiple values

Functions in Python can return multiple variables without the need for dictionaries, lists, or classes. It works as follows:

Defget_user (id): # fetch user from database #.... Return name, birthdate name, birthdate = get_user (4)

Viewrawreturn_multiple_variables.py hosted with ❤ by GitHub

This is fine for a limited number of return values. But anything with more than three values should be placed in a (data) class.

7. Working with data classes

Since version 3. 7, Python has provided data classes. Compared with regular classes or other alternatives, such as returning multiple values or dictionaries, there are several advantages:

A data class requires the least code

You can compare data classes because _ eq__ has been implemented

You debug by easily printing a data class because you also implement _ repr__

Data classes require type prompts to reduce the chance of errors. Here is an example of a data class:

From dataclasses import dataclass @ dataclass classCard: rank: str suit: str card = Card ("Q", "hearts") print (card = = card) # True print (card.rank) #'Q' print (card) Card (rank='Q', suit='hearts'

Viewrawdataclass.py hosted with ❤ by GitHub

Click here to view the high-level guide.

8. Variable exchange

A few lines of code can be omitted with a little trick.

A = 1 b = 2 a, b = b, a print (a) # 2 print (b) # 1

Viewrawin_place_variable_swapping.py hosted with ❤ by GitHub

9. Merge Dictionary (Python3.5+)

Since Python3.5, merging dictionaries has been easier

Dict1 = {'averse: 1,' baked: 2} dict2 = {'baked: 3,' clocked: 4} merged = {* * dict1, * * dict2} print (merged) # {'astat1,' baked: 3, 'cased: 4}

Viewrawmerging_dicts.py hostedwith ❤ by GitHub

If there are overlapping values, the values from the first dictionary will be overwritten.

10. Title case

This is just one of the interesting ways to play:

Mystring = "10 awesome python tricks" print (mystring.title ())'10 Awesome Python Tricks'

Viewrawstring_to_titlecase.py hosted with ❤ by GitHub

11. Cut string to list

You can split a string into a list of strings. In the following example, cut according to the space

Mystring = "The quick brown fox" mylist = mystring.split ('') print (mylist) # ['The',' quick', 'brown',' fox']

Viewrawstring_to_list.py hosted with ❤ by GitHub

twelve。 Create a string from the list of strings

Contrary to the previous technique, in this case, create a string from the list of strings and enter spaces between words:

Mylist = ['The',' quick', 'brown',' fox'] mystring = ".join (mylist) print (mystring) # 'The quick brown fox'

Viewrawlist_to_string.py hostedwith ❤ by GitHub

You may be wondering why you don't use mylist.join (""). Good question!

In the final analysis, the String.join () function can join not only lists, but also any list that can be iterated. Putting it in String prevents the same functionality from being implemented in multiple locations.

13. Expression

The expression is either happy or disagreeable, depending on the expression. More importantly, it is particularly useful when analyzing social media data. First, download the expression module

Pip3install emoji

After downloading, you can do the following:

Import emoji result = emoji.emojize ('Python is: thumbs_up:') print (result) #' Python is?'# You can also reverse this: result = emoji.demojize ('Python is?') Print (result) # 'Python is: thumbs_up:'

Viewrawemoji.py hosted with ❤ by GitHub

14. Make a list slice

Syntax of list slices:

A [start:stop:step]

Start, stop and step are all optional. If not set, the default value is

Start value is 0

End is the end of the string

Step value is 1

Here is an example:

# We can easily create a new list from # the first two elements of a list: first_two = [1,2,3,4,5] [0:2] print (first_two) # [1,2] # And if we use a step value of 2, # we can skip over every second number # like this: steps = [1,2,3,4,5] [0:5:2] print (steps) # [1,3,5] # This works on strings too. In Python, # you can treat a string like a list of # letters: mystring = "abcdefdn nimt" [:: 2] print (mystring) # 'aced it'

Viewrawlist_slicing.py hosted with ❤ by GitHub

15. Reverse strings and lists

Use the above slice symbol to reverse the string or list. Reverse the element by using a negative step value of-1:

Revstring = "abcdefg" [::-1] print (revstring) # 'gfedcba' revarray = [1,2,3,4,5] [::-1] print (revarray) # [5,4,3,2,1]

Viewrawreversing_stuff.py hosted with ❤ by GitHub

16. Show kittens

First, install Pillow, a branch of the Python image library:

Pip3install Pillow

Download this picture and name it kittens.jpg:

Image source TheDigitalArtist Pixabay

You can use the following code to display the image in the Python code: or you can use IPython directly:

FromPILimport Image im = Image.open ("kittens.jpg") im.show () print (im.format, im.size, im.mode) # JPEG (1920, 1357) RGB

Viewrawpillow.py hosted with ❤ by GitHub

In addition to displaying images, Pillow can also analyze, resize, filter, enhance, deform, and so on. Refer to the documentation for all its features.

17. Use map ()

One built-in function of Python is map (). The syntax of map () is: map (function, something_iterable) gives a function to execute and some variables to run. It can be any iterating element. In the following example, I will use a list.

Defupper (s): return s.upper () mylist = list (map (upper, ['sentence',' fragment']) print (mylist) # ['SENTENCE',' FRAGMENT'] # Convert a string representation of # a number into a list of ints. List_of_ints = list (map (int, "1234567")) print (list_of_ints) # [1,2,3,4,5,6,7]

Viewrawmap.py hostedwith ❤ by GitHub

Look at your code and see if you can use map () somewhere instead of a loop!

18. Extract unique elements from lists and strings

By creating a collection using the set () function, you can get all the unique elements from a list or similar list of objects:

Mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6] print (set (mylist)) # {1, 2, 3, 4, 5, 6} # And since a string can be treated like a # list of letters, you can also get the # unique letters from a string this way: print (set ("aaabbbcccdddeeefff"))

Viewrawset.py hosted with ❤ by GitHub

19. Find the value with the highest frequency

Find the most common value in a list or string:

Test = [1,2,3,4,2,2,3,1,4,4] print (max (set (test), key= test.count)) # 4

Viewrawmost_frequent.py hostedwith ❤ by GitHub

Do you understand why this is happening? Try to find out the answer for yourself before you continue to read. Haven't you tried yet? I'm going to tell you the answer.

Max () returns the maximum value in the list. The key parameter accepts a single parameter function to customize the sort order, which in this case is test.count. This function applies to every project on iterable.

test. Count is a built-in list function. It accepts a parameter and calculates the number of occurrences of that parameter. So test.count (1) will return 2 and test.count (4) will return 4.

Set (test) returns all the unique values in test, so {1Magne 2je 3je 4} so what we do in this line of code is to get all the unique values of test, that is, {1pm 2je 3je 4}. Next, max will apply the list.count function and return the maximum value.

20. Create a progress bar

It's interesting to create your own progress bar. But using progress packages is faster:

Pip3install progress

You can now spend less time creating a progress bar

From progress.bar import Bar bar = Bar ('Processing', max=20) for i inrange (20): # Do some work bar.next () bar.finish ()

Viewrawprogress_bar.py hostedwith ❤ by GitHub

21. Use _ in the interactive window

You can use the underscore operator to get the result of the last expression, for example, in IPython, as follows:

In [1]: 3 * 3 Out [1]: 9In [2]: _ + 3 Out [2]: 12

This also applies to Pythonshell. In addition, IPython shell allows you to use out [n] to get the value of an expression in [n]. For example, Out [1] gives the number 9.

twenty-two。 Quickly create a web server

Quickly start the web server to provide the contents of the current directory:

Python3-m http.server

This is useful if you want to share some content with colleagues, or if you want to test a simple HTML site.

23. Multiline string

Although you can use three quotes to include multiple lines of strings in your code, this is not ideal. Everything placed between the three quotation marks becomes a string, including the format, as shown below.

I prefer the second method, which concatenates multiple lines together so that you can format the code well. The only drawback is that you need to explicitly add newline characters.

S1 = "" Multi line strings can be put between triple quotes. It's not ideal when formatting your code though "" print (S1) # Multi line strings can be put # between triple quotes. It's not ideal # when formatting your code though S2 = ("You can also concatenate multiple\ n" + "strings this way, but you'll have to\ n"explicitly put in the newlines") print (S2) # You can also concatenate multiple # strings this way, but you'll have to # explicitly put in the newlines

Viewrawmultiline_strings.py hosted with ❤ by GitHub

24. Ternary operator for conditional assignment

This is another way to make your code both concise and readable: [on_true] if [expression] else [on _ false] example:

X = "Success!" If (yearly = 2) else "Failed!"

25. Calculation frequency

Use the Counter in the collection library to get a dictionary that contains the count of all unique elements in the list:

From collections import Counter mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6] c = Counter (mylist) print (c) # Counter ({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2}) # And it works on strings too: print (Counter ("aaaaabbbbbccccc")) # Counter ({'aqu: 5, 'baked: 5,' cased: 5})

Viewrawcounter.py hosted with ❤ by GitHub

twenty-six。 Link comparison operator

Link the comparison operator in Python to create more readable and concise code:

X = 10 # Instead of: if x > 5and x

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