[experience sharing] 30 Python programming practices, suggestions and skills

What new Flag did you set up in 2020? Anyway, as long as we are learning programming and using python, we are all a family! Let's prepare 30 excellent Python practice skills for you. I hope that these tips can help you in practical work and learn some useful knowledge.

1. Using python 3

Most of the examples in this tutorial can only be run in the python 3 environment because the official support for updates to python2.7 has been stopped since January 1, 2020. If you are still using version 2.7, upgrade to Python 3 first.

2. Check and use the minimum python version that meets the requirements

You can check the Python version in your code to make sure that your code consumer is not running the script with an incompatible version. Use the following code for a simple check:

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

3. Using IPython

IPython is basically an enhanced shell. It's just for auto completion. IPython is also worth using. But in fact, it has more functions, including the built-in Magic command. Here are some examples:

  • %cd: change the current working directory

  • %edit: open the editor and execute the typed code after closing the editor

  • %env: displays the current environment variable

  • %pip: install [pkgs] install feature pack without leaving interactive shell

  • %Time and% timeit: similar to the time module in python, you can time code

Another useful feature of IPython is that you can use the output of any previous line of code. The input and input of code are actually objects. For example, you can use the output object of the third run of code through Out[3]. The instructions for installing IPython are:

pip3 install ipython

4. List parsing

List parsing can be used to replace the ugly method of filling list through loop. Its basic syntax is:

[ expression for item in list if conditional ]

A very basic example for generating a list of consecutive numbers:

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

Because you can use expressions, you can generate lists in more complex mathematical ways:

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

You can even call external functions:

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

Finally, you can use if as the generation condition to filter the list. In the following example, only even numbers are retained:


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

5. Check the memory usage of objects

With the sys.getsizeof(object) command, you can view the memory usage of any object:


What I don't know in the learning process can add to me
 python learning qun, 855408893
 There are good learning video tutorials, development tools and e-books in the group.
Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn 

import sys

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

This is because the range function returns a class object, which is represented as a list. So using the range function saves more memory than using an actual list of 10000 numbers. You can create an actual list of the same size through the list parsing mentioned in Article 4 above:

import sys

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

The actual memory consumption is 87632 bytes, which is much higher than the object generated by the range function.

6. Return multiple values

Functions in Python can return multiple variables without dictionary, list or class as the return object. The method is as follows:

def get_user(id): # fetch user from database
    # ....
    return name, birthdate

name, birthdate = get_user(4)

For a limited number of return values, this is OK. But anything with more than three values should be put into a (data) class.

7. Using the data class

Since version 3.7, python has provided data classes. There are several advantages over regular classes or other alternative methods, such as returning multiple values or dictionaries:

  • Data classes require at least a certain amount of code

  • You can compare different data class objects through eq method

  • You can repr debug by easily printing a data class

  • Data classes need type hints, so bug s are reduced

An example of a data class is as follows:

from dataclasses import dataclass

@dataclass class Card:
    rank: str
    suit: str

card = Card("Q", "hearts") print(card == card) # True

print(card.rank) # 'Q'

print(card)
Card(rank='Q', suit='hearts')

8. Local variable exchange

A simple technique can save several lines of code:

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

9. Dictionary merge (Python 3.5 +)

Starting with python 3.5, dictionary merging has become easier:

dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = { **dict1, **dict2 } print (merged) # {'a': 1, 'b': 3, 'c': 4}

10. Convert string to Title Format

In the title format, the initial of a non preposition is capitalized. You can do this through the. title() method:

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

11. Detaches strings and stores them in a list

You can divide a string by any character and store it in a list, for example, by space:

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

12. Combine strings from the list

Instead of the previous one, create a string from the list and insert a space between the two words:

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

You may wonder, why not use mylist.join("")? At the end of the day, the String.join() function can connect not only lists, but any list that can be iterated. Putting it in a String prevents the same functionality from being implemented in multiple locations.

13,Emoji

These expressions have strong expressive ability and can leave a deep impression. More importantly, this is particularly useful when analyzing social media data. First install the emoji module with the following command:

pip3 install emoji

You can use emoticons as follows:

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:'

14. List slice operation

The basic syntax of list slicing is:

a[start:stop:step]

start, stop and step are optional (optional). The default value is:

  • start: 0

  • stop: end of list

  • step: 1

Some examples are as follows:


//What I don't know in the learning process can add to me
python Study qun,855408893
//There are good learning video tutorials, development tools and e-books in the group.
//Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn 

# 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'

15. Flip strings and lists

You can use the slice operation to flip the list or string and set the step to a negative value

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

16. Picture display

You can use the pilot module to display pictures, such as Kitty Kitty. First install the python picture library:

pip3 install Pillow

Then download the picture you want to display and rename it. You can then display the picture with the following command:


from PIL import Image

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

Or it can be displayed directly through IPython:

Pillow's capabilities go far beyond displaying pictures. It can analyze, resize, filter, enhance, transform and so on.

17. Using the map() function

One of Python's built-in functions is map(). The basic syntax of map() is:

map(function, something_iterable)

The parameter passed in is a function, and an object to execute, which can be any iteratable object. In the following example, list is used:

#python learning group 855408893
def upper(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]

map() is a good alternative to loops, and you can try using the map() function in your code.

18. Get unique elements from a list or string

With the set() function, you can convert a list or string to a set, which contains no duplicate elements:

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")) # {'a', 'b', 'c', 'd', 'e', 'f'}

19, Find the most common value

Find the most frequent value in a list or string:

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

You can try to understand the code yourself. Well, maybe you didn't try. The above code works as follows:

  • max() returns the maximum value in the list. The key parameter takes a single parameter function to determine the custom sort order. In this case, it is test.count, which is applied to each element in the iterable object.

  • . count() is a built-in function of the list that takes a parameter and calculates the number of times it appears. So in this case, test.count(1) returns 2, and testcount(4) returns 4.

  • set(test) returns all unique values in the test list, so it is {1,2,3,4}.

So in the above statement, we first find all the unique values of the test list, namely {1,2,3,4}. Next, apply the. count function to each value in the set to get a list of quantities, and then find out the maximum value through max.

20. Create progress bar

You can create a progress bar by yourself, but you can also create it quickly through the progress module:

pip3 install progress

Then create a progress bar with the following code:

from progress.bar import Bar

bar = Bar('Processing', max=20) for i in range(20): # Do some work
 bar.next()
bar.finish()

The effect is as follows:

21. In the interactive shell, you can use the underline operator to get the output of the last run expression by using UU to get the run result of the previous expression. The operation in IPython is as follows:

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

This method is also applicable in python shell. IPython can also get the output of any nth expression through Out[n].

22. Quickly create a web server

You can quickly start the web server to provide the contents of the current working 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 triple quotes to include multiline strings in your code, this is not ideal. Everything between three quotes becomes a string, including the format. I prefer the second approach, which links multiple lines together and allows you to format your code well. The only disadvantage is that you need to explicitly put new rows:

pip3 install python-dateutil 
pip3 install python-dateutil 

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

24. Ternary operator for conditional assignment. This is another way to make your code concise and readable:

[on_true] if [expression] else [on_false]

A simple example is as follows:

x = "Success!" if (y == 2) else "Failed!"

25. Count the number of elements

You can use the Counter method in the Collections dependency package 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({'a': 5, 'b': 5, 'c': 5})

26. The connection of comparison operators can link comparison operators in python to make the code more concise and readable:

x = 10
# Instead of:
if x > 5 and x < 15: print("Yes") # yes # You can also write:
if 5 < x < 15: print("Yes") # Yes

27. Add color

Through Colorama dependency package, you can add more colors to the terminal:

pip3 install python-dateutil 
 from colorama import Fore, Back, Style print(Fore.RED + 'some red text') print(Back.GREEN + 'and with a green background') print(Style.DIM + 'and in dim text') print(Style.RESET_ALL) print('back to normal now')

28. Date processing

The python dateutil module provides a powerful extension to the standard datetime module. First install the module:

pip3 install python-dateutil 

You can do a lot of cool things with this library. I will take a function that I think is particularly useful as an example: fuzzy resolution of dates in log files, etc. As follows:

#python learning group 855408893
from dateutil.parser import parse
logline = 'INFO 2020-01-01T00:00:01 Happy new year, human.' timestamp = parse(log_line, fuzzy=True) print(timestamp) # 2020-01-01 00:00:01

Just remember that if datatime does not have a function, datautil must have that function, and datautil is the continuation of datatime function.

29. Division

In Python 2, the division operator (/) defaults to integer division unless one of the operands is a floating-point number. As follows:

# Python 2
5 / 2 = 2
5 / 2.0 = 2.5

In Python 3, the division operator / default is floating-point division, and the / / operator becomes integer division. So there are:

Python 3
5 / 2 = 2.5
5 // 2 = 2

30. Detect character set through chardet

You can use the chardet module to detect character sets in a file. This is useful when analyzing large amounts of random text. To install the chardet module:

pip install chardet

Now you have an additional command-line tool, chardetect, which can be used as follows:

chardetect somefile.txt
somefile.txt: ascii with confidence 1.0

You can also use this dependency package programmatically. These are 30 python tips. I hope these tips can help you get a good start in the new year.

Tags: Programming Python IPython emoji shell

Posted on Mon, 27 Apr 2020 04:25:19 -0400 by rp2006