In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you 25 super useful Python code snippets, which are concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Python is a general-purpose high-level programming language. You can do a lot of things with it, such as developing desktop GUI applications, websites, and Web applications.
As a high-level programming language, Python also allows you to focus on the core functions of your application by dealing with common programming tasks. Moreover, the simple syntax rules of the programming language further simplify the readability of the code base and the maintainability of the application.
Compared with other programming languages, Python has the following advantages:
Compatible with major platforms and operating systems
There are many open source frameworks and tools
The code is readable and maintainable
A robust standard library
Standard test-driven development
In this article, I will introduce 25 short and useful code snippets that can help you with your daily tasks.
1. Exchange values between two variables
In other languages, to exchange values between two variables instead of using the third variable, we use either the arithmetic operator or Bitwise XOR. In Python, it is much simpler, as shown below.
A = 5b = 10a 10print b = b me aprint (a) # aprint (b) # 5
2. Check whether the given number is even
If the given number is even, the following function returns Ture, otherwise it returns False.
Def is_even (num): eturn num% 2 = = 0 is_even (10) # True
3. Split a multiline string into a list of lines
The following function can be used to split a multiline string into a list of rows.
Def split_lines (s): return s.split ('n') split_lines ('50n pythonn snippets') # [' 50th, 'python',' snippets']
4. Find the memory used by the object
The sys module of the standard library provides the getsizeof () function. This function takes an object, calls the object's sizeof () method, and returns the result, which makes the object inspectable.
Import sysprint (sys.getsizeof (5)) # 28print (sys.getsizeof ("Python")) # 55
5. Reverse the string
The Python string library does not support the built-in reverse () like other Python containers such as list. There are many ways to reverse strings, the easiest of which is to use the slice operator (slicing operator).
Language = "python" reversed_language = language [::-1] print (reversed_language) # nohtyp
6. Print the string n times
It is very easy to print a string n times without using a loop, as shown below.
Def repeat (string, n): return (string * n) repeat ('python', 3) # pythonpythonpython
7. Check whether the string is a palindrome
The following function is used to check whether the string is a palindrome.
Def palindrome (string): return string = = string [::-1] palindrome ('python') # False
8. Merge the list of strings into a single string
The following code snippet combines a list of strings into a single string.
Strings = ['50 girls, 'python',' snippets'] print (', '.join (strings)) # 50 century pythonje snippets
9. Find the first element of the list
This function returns the first element of the passed list.
Def head (list): return list [0] print (head ([1,2,3,4,5])) # 1
10. Find elements that exist in either of the two lists
This function returns each element in either of the two lists.
Def union (set (a + b)): return list (set (a + b)) union ([1, 2, 8, 1, 4]) # [1, 2, 8, 1, 4]
11. Find all unique elements in a given list
This function returns the only element that exists in the given list.
Def unique_elements (numbers): return list (set (numbers)) unique_elements ([1,2,3,2,4]) # [1,2,3,4]
12. Find the average of a set of numbers
This function returns the average of two or more numbers in the list.
Def average (* args): return sum (args, 0.0) / len (args) average (5,8,2) # 5.0
13. Check whether the list contains all unique values
This function checks whether all elements in the list are unique.
Def unique (list): if len (list) = = len (set (list)): print ("All elements are unique") else: print ("List has duplicates") unique
14. Track the frequency of elements in the list
The Python counter tracks the frequency of each element in the container. Counter () returns a dictionary with the element as the key and its occurrence frequency as the value.
From collections import Counterlist = [1, 2, 3, 2, 4, 3, 2, 3] count = Counter (list) print (count) # {2: 3,3: 3,1: 1,4: 1}
15. Find the most commonly used elements in the list
This function returns the element that appears most frequently in the list.
Def most_frequent (list): return max (set (list), key = list.count) numbers = [1,2,3,2,4,3,1,3] most_frequent (numbers) # 3
16. Convert the angle to radians
The following function is used to convert angles to radians.
Import mathdef degrees_to_radians (deg): return (deg * math.pi) / 180.0 degrees_to_radians (90) # 1.5707963267948966
17. Calculate the time it takes to execute a piece of code
The following code snippet is used to calculate the time required to execute a piece of code.
Import timestart_time = time.time () a Time taken in micro_seconds b = 5Power10 c = a+bend_time = time.time () time_taken = (end_time- start_time) * (10 minutes 6) print ("Time taken in micro_seconds:", time_taken) # Time taken in micro_seconds: 39.577484130859375
18. Find the maximum common divisor of the list of numbers
This function calculates the maximum common divisor in the list of numbers.
From functools import reduceimport mathdef gcd (numbers): return reduce (math.gcd, numbers) gcd ([24, 108, 90]) # 6
19. Find the unique character in the string
This code snippet can be used to find all unique characters in a string.
String = "abcbcabdb" unique = set (string) new_string = '.join (unique) print (new_string) # abcd
20. Use lambda function
Lambda is an anonymous function that can hold only one expression.
X = lambda a, b, c: a + b + cprint (x (5,10,20)) # 35
21. Use mapping functions
This function returns a list of results after applying a given function to each item (list, tuple, and so on) of a given iteration.
Def multiply (n): return n * n list = (1,2,3) result = map (multiply, list) print (list (result)) # {1,4,9}
22. Use the filter function
This function filters the given sequence through a function to test whether each element in the sequence is true.
Arr = [1,2,3,4,5] arr = list (filter (lambda x: X% 2 = = 0, arr)) print (arr) # [2,4]
23. Use list to parse
List parsing (list comprehensions) provides us with an easy way to create lists based on some iterations. During the creation process, elements from iterations can be conditionally included in the new list and transformed as needed.
Numbers = [1,2,3] squares = [number**2 for number in numbers] print (squares) # [1,4,9]
24. Use the slice operator
A Slicing is used to extract a continuous sequence of elements or subsequences from a given sequence. The following function is used to connect the results of two slice operations. First, we slice the list from index d to the end, and then from the beginning to index d.
Def rotate (arr, d): return arr [d:] + arr [: d] if _ name__ = ='_ main__': arr = [1,2,3,4,5] arr = rotate (arr, 2) print (arr) # [3,4,5,1,2]
25. Use function chained calls
The last code snippet is used to call multiple functions from one line and evaluate the result.
Def add (a, b): return a + bdef subtract (a, b): return a-ba, b = 5, 10print ((subtract if a > b else add) (a, b)) # 15
The above are the 25 super useful Python code snippets. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.