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
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
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']
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
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
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
The following function checks if the string is palindrome .
def palindrome(string):
return string == string[::-1]
palindrome('python') # False
The following code snippet combines a list of strings into a single string .
strings = ['50', 'python', 'snippets']
print(','.join(strings)) # 50,python,snippets
This function returns the first element of the list passed .
def head(list):
return list[0]
print(head([1, 2, 3, 4, 5])) # 1
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]
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]
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
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
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}
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
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
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
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
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
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
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}
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]
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]
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]
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 …