Introduction to 15 Python tips

Author : xuzhiping   2023-02-08 14:22:01 Browse: 928
Category : Python

Abstract: 1.Display cat I finally found a sufficient excuse to show cats in my article. Of course, you can also use it to display pictures...

1.Display cat

I finally found a sufficient excuse to show cats in my article. Of course, you can also use it to display pictures. First, you need to install Pillow, which is a branch of Python image library:

pip3 install Pillow

Next, you can download the following image to a file named kittens.jpg:

Cats

Then, you can display the above image through the following Python code:

from PIL import Image

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

Pillow has many other functions besides displaying the picture. It can analyze, resize, filter, enhance, deform, and so on.

2.map()

Python has a built-in function called 'map()'. The syntax is as follows:

map(function, something_iterable)

Therefore, you need to specify a function to execute, or something to execute. Any iterable object can. In the following example, I specify a list:

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]

You can take a closer look at your code to see if you can replace a loop somewhere with map().

3.Get the unique element in the list or string

If you use the function set() to create a collection, you can obtain the unique elements of a list or list-like 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"))
# {'a', 'b', 'c', 'd', 'e', 'f'}

4.Find the value with the highest frequency

You can find the value with the highest frequency by the following methods:

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

Can you understand the above code? Read on after understanding the above code. Do not understand? Let me tell you:

  • max() will return the maximum value of the list. The parameter key will accept a parameter function to define the sort. In this case, it is test. count. This function is applied to each item of the iteration object.

  • test. count is a built-in function of list. It accepts a parameter and calculates the number of occurrences of the parameter. Therefore, test. count (1) will return 2, while test. count (4) will return 4.

  • set (test) will return all the unique values in test, -that is, {1, 2, 3, 4}.

Therefore, the operation completed by this line of code is: first obtain all the unique values of test, namely {1, 2, 3, 4}; Then, max will execute list. count for each value and return the maximum value.

5.Create a progress bar

You can create your own progress bar, which sounds interesting. However, the simpler method is to use the progress package:

pip3 install progress

Next, you can easily create a progress bar:

from progress.bar import Bar

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

6.Use in interactive shell _ (underscore operator)

You can get the result of the last expression through the underscore operator. For example, in IPython, you can do this:

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

This can also be used in Python shell. In addition, in the IPython shell, you can also get the value of the expression In [n] through Out [n]. For example, in the above example, out [1] will return the number 9.

7.Quickly create a web server

You can quickly start a web service and provide the contents of the current directory:

python3 -m http.server

When you want to share a file with colleagues or test a simple HTML site, you can consider this method.

8.Multiline string

Although you can use triple quotation marks to enclose multiple lines of string in the code, this is not ideal. All content placed between triple quotation marks will become a string, including the format of the code, as shown below.

I prefer another method, which can not only connect multiple lines of strings together, but also ensure the cleanness of the code. The only disadvantage is that you need to specify the newline character explicitly.

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

9.Ternary operator in conditional assignment

This method can make the code more concise and ensure the readability of the code at the same time:

[on_true] if [expression] else [on_false]

10.Number of occurrences of statistical elements

You can use the Counter in the collection library to get the number of occurrences of all unique elements in the list. The Counter will return a dictionary:

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})

You can link multiple comparison operators together in Python, so that you can create more readable and concise code:

x = 10

# Instead of:
if x > 5 and x < 15:
    print("Yes")
# yes

# You can also write:
if 5 < x < 15:
    print("Yes")
# Yes

12.Add color

Add color

You can set the display color of the terminal through Color:

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

13.Date processing

As a supplement to the standard date module, the python-dateutil module provides a very powerful extension. You can install it with the following command:

pip3 install python-dateutil

You can use this library to complete many magical operations. Here I just give an example: fuzzy analysis of the date in the log file:

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

You just need to remember that when you encounter problems that cannot be solved by the regular Python datetime function, you can consider python-dateutil!

14.Integer division

Integer division

In Python 2, the division operator (/) defaults to integer division, unless one of the operands is a floating point number. Therefore, you can write as follows:

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

In Python 3, the division operator (/) defaults to floating point division, while the integer division operator is//. Therefore, you need to write:

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

For the motivation behind this change, see:

PEP-0238(https://www.python.org/dev/peps/pep-0238/)。

15.Detect character set through chardet

You can use the chardet module to detect the character set of a file. This module is very practical when analyzing a large number of random texts. The installation method is as follows:

pip install chardet

After the installation is completed, you can use the command line tool chardetect, as follows:

chardetect somefile.txt
somefile.txt: ascii with confidence 1.0
Label :
    Sign in for comments!
Comment list (0)

Powered by TorCMS (https://github.com/bukun/TorCMS).