Table of Contents
1. Uniqueness
2. Anagrams (words with the same letters in different orders)
3. Memory
4. Byte size
5. Print a string N times
6. Capitalize the first letter
7. List subdivision
8. Compression
9. Counting
10. Chain comparison
11. Comma separated
12. Vowel counting
13. The first letter is lowercase
24. Expand the list
15. Find the difference
16. Output the difference
17. Chain function call
18.
19. Convert two lists into fonts
20. The element with the highest frequency of occurrence
21. Palindrome (the same string is read forward and backward)
22. Calculator without if-else statements
23. Random sorting
Home Backend Development Python Tutorial What are some very practical Python skills?

What are some very practical Python skills?

May 12, 2023 pm 05:34 PM
python

1. Uniqueness

The following method can check whether there are duplicates in a given list, and use the set() attribute to delete them from the list.

x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
len(x)== len(set(x)) # False
len(y)== len(set(y)) # True
Copy after login

2. Anagrams (words with the same letters in different orders)

This method can be used to check whether two strings are anagrams.

from collections import Counter
>>> Counter('abadfsdafsdfjsdaf')
Counter({'a': 4, 'd': 4, 'f': 4, 's': 3, 'b': 1, 'j': 1})

def anagram(first, second):
    return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
Copy after login

3. Memory

This code snippet can be used to check the memory usage of an object.

import sys 
variable = 30 
print(sys.getsizeof(variable)) # 28
Copy after login

4. Byte size

This method can output the byte size of the string.

print(len(''.encode('utf-8')))# 0
print(len('hellow sdfsdaf'.encode('utf-8'))) # 14
Copy after login

This code segment can print a string multiple times without looping.

n = 2; 
s ="Programming"; 
print(s * n); # ProgrammingProgramming
Copy after login

6. Capitalize the first letter

The following code snippet only uses title() to capitalize the first letter of each word in the string.

s = "programming is awesome"
print(s.title()) # Programming Is Awesome
Copy after login

7. List subdivision

This method subdivides the list into lists of a specific size.

>>> list = list(range(12))
>>> size=3
>>> [list[i:i+size] for i in range(0,len(list), size)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
>>>
Copy after login

8. Compression

The following code uses filter() to remove error values ​​(False, None, 0 and " ") from the list.

list(filter(bool, [0, 1, False, 2, '', 3, 'a', 's', 34]))
Copy after login

9. Counting

The following code can be used to swap the 2D array arrangement.

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed)  # [('a', 'c', 'e'), ('b', 'd', 'f')]
Copy after login

10. Chain comparison

The following code can perform multiple comparisons on various operators.

a = 3
print( 2 < a < 8) # True
print(1 == a < 2) # False
Copy after login

11. Comma separated

This code snippet converts a list of strings into a single string while separating each element in the list with a comma.

hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming
Copy after login

12. Vowel counting

This method can count the number of vowels ("a", "e", "i", "o", "u") in the string .

import re
print(len(re.findall(r&#39;[aeiou]&#39;, &#39;foobar&#39;, re.IGNORECASE)))   # 3
print(len(re.findall(r&#39;[aeiou]&#39;, &#39;gym&#39;, re.IGNORECASE)))   # 0
Copy after login

13. The first letter is lowercase

This method converts the first letter of the given string into lowercase mode.

&#39;FooBar&#39;[:1].lower() + &#39;FooBar&#39;[1:] # &#39;fooBar&#39;
&#39;FooBar&#39;[:1].lower() + &#39;FooBar&#39;[1:]   # &#39;fooBar&#39;
Copy after login

14. Expand the list

The following code uses a recursive method to expand a potentially deep list.

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
    else:
        ret.append(i)
    return ret

def deep_flatten(lst):
    result = []
    result.extend(
        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
    return result
deep_flatten([1, [2], [[3], 4], 5])  # [1,2,3,4,5]
print(deep_flatten([1, [2], [[3], 4], 5]))  # [1,2,3,4,5]
Copy after login

15. Find the difference

This method keeps only the values ​​in the first iteration to find the difference between the two iterations

set([1,2,3])-set([1,2,4]) # [3]
Copy after login

16. Output the difference

The following method uses existing functions to find and output the difference between two lists.

def difference_by(a, b, fn):
    b = set(map(fn, b))
    return [item for item in a if fn(item) not in b]
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ &#39;x&#39;: 2 }, { &#39;x&#39;: 1 }], [{ &#39;x&#39;: 1 }], lambda v : v[&#39;x&#39;]) # [ { x: 2 } ]
Copy after login

17. Chain function call

The following method can call multiple functions in one line

def add(a, b):
    return a + b
def subtract(a, b):
    return a – b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9
Copy after login

18.

In Python3.5 and In the upgraded version, you can also execute the step code in the following way:

def merge_dictionaries(a, b):
    return {**a, **b}
a = { &#39;x&#39;: 1, &#39;y&#39;: 2}
b = { &#39;y&#39;: 3, &#39;z&#39;: 4}
print(merge_dictionaries(a, b)) # {&#39;y&#39;: 3, &#39;x&#39;: 1, &#39;z&#39;: 4}
Copy after login

19. Convert two lists into fonts

The following method can convert two lists into fonts.

keys = ["a", "b", "c"] 
values = [2, 3, 4]
print(dict(zip(keys, values))) # {&#39;a&#39;: 2, &#39;c&#39;: 4, &#39;b&#39;: 3}
Copy after login

20. The element with the highest frequency of occurrence

This method will output the element with the highest frequency of appearance in the list.

def most_frequent(list):
    return max(set(list), key = list.count)
list = [1,2,1,2,3,2,1,4,2]
most_frequent(list)
Copy after login

21. Palindrome (the same string is read forward and backward)

The following code checks whether the given string is a palindrome. First convert the string to lowercase, then remove non-alphabetic characters from it, and finally compare the new string version to the original version.

def palindrome(string):
    from re import sub
    s = sub(&#39;[\W_]&#39;, &#39;&#39;, string.lower())
    return s == s[::-1]
palindrome(&#39;taco cat&#39;) # True
Copy after login

22. Calculator without if-else statements

The following code snippet shows how to write a simple calculator without if-else conditional statements.

import operator
action = {
 "+": operator.add,
 "-": operator.sub,
 "/": operator.truediv,
 "*": operator.mul,
 "**": pow
}
print(action[&#39;-&#39;](50, 25)) # 25
Copy after login

23. Random sorting

This algorithm uses the Fisher-Yates algorithm to randomly sort the elements in the new list.

from copy import deepcopy
from random import randint

def shuffle(lst):
    temp_lst = deepcopy(lst)
    m = len(temp_lst)
    while (m):
        m -= 1
    i = randint(0, m)
    temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
    return temp_lst

foo = [1, 2, 3]
shuffle(foo)  # [2,3,1] , foo = [1,2,3]
Copy after login

24. Expand the list

This method can only expand 2 levels of nested lists, not more than 2 levels

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret
spread([1, 2, 3, [4, 5, 6], [7], 8, 9])  # [1,2,3,4,5,6,7,8,9]
print(spread([1, 2, 3, [4, 5,[10,11,12,132,4,[1,2,3,4,5,6]], 6], [7], 8, 9]))  #[1, 2, 3, 4, 5, [10, 11, 12, 132, 4, [1, 2, 3, 4, 5, 6]], 6, 7, 8, 9]
Copy after login

The above is the detailed content of What are some very practical Python skills?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to choose the PyTorch version on CentOS How to choose the PyTorch version on CentOS Apr 14, 2025 pm 06:51 PM

When installing PyTorch on CentOS system, you need to carefully select the appropriate version and consider the following key factors: 1. System environment compatibility: Operating system: It is recommended to use CentOS7 or higher. CUDA and cuDNN:PyTorch version and CUDA version are closely related. For example, PyTorch1.9.0 requires CUDA11.1, while PyTorch2.0.1 requires CUDA11.3. The cuDNN version must also match the CUDA version. Before selecting the PyTorch version, be sure to confirm that compatible CUDA and cuDNN versions have been installed. Python version: PyTorch official branch

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

See all articles