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
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
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
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
5. Print a string N times
This code segment can print a string multiple times without looping.
n = 2; s ="Programming"; print(s * n); # ProgrammingProgramming
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
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]] >>>
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]))
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')]
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
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
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'[aeiou]', 'foobar', re.IGNORECASE))) # 3 print(len(re.findall(r'[aeiou]', 'gym', re.IGNORECASE))) # 0
13. The first letter is lowercase
This method converts the first letter of the given string into lowercase mode.
'FooBar'[:1].lower() + 'FooBar'[1:] # 'fooBar' 'FooBar'[:1].lower() + 'FooBar'[1:] # 'fooBar'
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]
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]
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([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
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
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 = { 'x': 1, 'y': 2} b = { 'y': 3, 'z': 4} print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
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))) # {'a': 2, 'c': 4, 'b': 3}
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)
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('[\W_]', '', string.lower()) return s == s[::-1] palindrome('taco cat') # True
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['-'](50, 25)) # 25
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]
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]
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!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)