程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The 25 most useful code snippets for Python

編輯:Python

Preface

Python Is a general high level programming language . There are many things you can do with it , For example, develop desktop GUI Applications 、 Website and Web Applications, etc .

As a high level programming language ,Python It also allows you to focus on the core functions of your application by handling common programming tasks . also , Simple language rules for programming languages

It further simplifies the readability of the code base and the maintainability of the application .

Compared with other programming languages ,Python The advantage is that :

1. Compatible with major platforms and operating systems ;
2. There are many open source frameworks and tools ;
3. The code is readable and maintainable ;
4. Robust standard library ;
5. Standard Test Driven Development

In this paper , I'll introduce you to 25 Short and useful code snippets , They 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 one , We either use arithmetic operators , Either use bitwise exclusive or (Bitwise XOR). stay

Python in , It's much simpler , As shown below .

a = 5
b = 10
a,b = b,
aprint(a) # 10
print(b) # 5

2. Check if the given number is even

If the given number is even , The following function returns Ture, Otherwise return to False.

python Exchange of learning Q Group :906715085###
def is_even(num):
return num % 2 == 0
is_even(10) # True

3. Split a multiline string into a list of rows

The following functions can be used to split a multiline string into a list of rows .

def split_lines(s):
return s.split('\n')
split_lines('50\n python\n snippets') # ['50', ' python', ' snippets']

4. Find the memory used by the object

Standard library sys The module provides getsizeof() function . This function takes an object , Call the object's sizeof() Method , And return the result , This makes the object checkable .

import sys
print(sys.getsizeof(5)) # 28
print(sys.getsizeof("Python")) # 55

5. Reverse string

Python String libraries are not like other Python Containers ( Such as list) That supports built-in reverse(). There are many ways to reverse strings , The easiest way is to use the slice operator (slicing operator).

language = "python"
reversed_language = language[::-1]
print(reversed_language) # nohtyp

6. Print string n Time

Without using the cycle , To print a string n It's very easy , As shown below .

def repeat(string, n):
return (string * n)
repeat('python', 3)
# pythonpythonpython

7. Check if the string is palindrome

The following function checks if the string is 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', 'python', 'snippets']
print(','.join(strings)) # 50,python,snippets

9. Find the first element of the list

This function returns the first element of the list passed .

def head(list):
return list[0]
print(head([1, 2, 3, 4, 5])) # 1

10. Find the elements that exist in either of the two lists

This function returns each element in any of the two lists .

def union(a,b):
return list(set(a + b))
union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4]) # [1,2,3,4,5,6,8]

11. Find all unique elements in a given list

This function returns the unique 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 figures

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 if 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([1,2,3,4,5]) # All elements are unique

14. Track the frequency of elements in the list

Python The counter tracks the frequency of each element in the container .Counter() Returns an element as a key 、 A dictionary whose frequency is taken as its value .

from collections import Counte
rlist = [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 most frequent element 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 functions are used to convert angles to radians .

import math
def degrees_to_radians(deg):
return (deg * math.pi) / 180.0
degrees_to_radians(90) # 1.5707963267948966

17. Calculate the time required to execute a piece of code

The following code snippet is used to calculate the time required to execute a piece of code .

import time
start_time = time.time()
a,b = 5,10
c = a+b
end_time = time.time()time_taken = (end_time- start_time)*(10**6)
print("Time taken in micro_seconds:", time_taken) # Time taken in micro_seconds: 39.577484130859375

18. Find the greatest common divisor of the number list

This function calculates the greatest 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 unique characters in a 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 , It can only hold one expression .

x = lambda a, b, c : a + b + c
print(x(5, 10, 20)) # 35

title 21. Use mapping functions

This function applies the given function to each item of a given iteration ( list 、 Tuples etc. ) after , Return a list of results .

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 , 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 parsing

List of analytical (list comprehensions) Provides a simple way for us to create lists based on some iterations . In the process of creation , Elements that can be iterated from can be conditionally included in the new list , And switch as needed .

numbers = [1, 2, 3]
squares = [number**2 for number in numbers]
print(squares) # [1, 4, 9]

24. Use slicing operators

section (Slicing) 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 will index the list from d Slice to end , Then slice from the beginning to the 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 chain call

The final code snippet is used to call multiple functions from one line and calculate the result .

def add(a, b):
return a + bdef subtract(a, b):
return a - ba, b = 5, 10
print((subtract if a > b else add)(a, b)) # 15

Last
That's the end of today's sharing , If you don't understand something, you can bring it up ! Smash the door see you in the next chapter …


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved