Picture from Jantine Doornbos on Unsplash
原标题 | 30 Helpful Python Snippets That You Can Learn in 30 Seconds or Less
Author |
Fatos Morina
Translation |
Pita & AI Developer
Python is currently one of the most popular languages. It is widely used by many people in data science, machine learning, web development, scripting, and automation. Its simplicity and ease of use make it so popular.
In this article, we will introduce 30 short code snippets, you can understand and learn these code snippets in 30 seconds or less.
1. Check for duplicate elements
The following method can check whether there are duplicate elements in a given list. It uses the set() attribute, which will remove duplicate elements from the list.
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True
2. Conjugation
Check whether two strings are anagrams (that is, reverse the order of characters)
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
3. Check the memory usage
The following code snippet can be used to check the memory usage of an object.
import sys
variable = 30
print(sys.getsizeof(variable)) # 24
4. Byte size calculation
The following method will return the length of the string in bytes.
def byte_size(string):
return(len(string.encode( utf-8 )))
byte_size( ? ) # 4
byte_size( Hello World ) # 11
5. Repeat printing string N times
The following code can print a string n times without using a loop
n = 2;
s ="Programming"; print(s * n);
# ProgrammingProgramming
6. Capitalize the first letter
The following code snippet uses the title() method to capitalize each word in the string.
s = "programming is awesome"
print(s.title()) # Programming Is Awesome
7. Blocking
The following method uses range() to block the list into smaller lists of a specified size.
from math import ceil
def chunk(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(0, ceil(len(lst) / size)))))
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
8. Compression
The following method uses fler() to delete the error values in the list (such as: False, None, 0 and "")
def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, , 3, a , s , 34]) # [ 1, 2, 3, a , s , 34 ]
9. Number of intervals
The following code snippet can be used to convert a two-dimensional array.
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 with various operators in one line.
a = 3
print( 2 < a < 8) # True
print(1 == a < 2) # False
11. Comma separated
The following code snippet can convert a list of strings into a single string, and each element in the list is separated by a comma.
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming
12. Count the number of vowels
The following method can count the number of vowels ('a','e','i','o','u') in a string.
import re
def count_vowels(str):
return len(len(re.findall(r [aeiou] , str, re.IGNORECASE)))
count_vowels( foobar ) # 3
count_vowels( gym ) # 0
13. The first letter is restored to lowercase
The following method can be used to convert the first letter of a given string to lowercase.
def decapitalize(string):
return str[:1].lower() + str[1:]
decapitalize( FooBar ) # fooBar
decapitalize( FooBar ) # fooBar
14. Planarization
The following method uses recursion to expand the list of potential depths.
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]
15. Difference
This method only keeps the value in the first iterator, thus discovering the difference between the two iterators.
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
difference([1,2,3], [1,2,4]) # [3]
16. Look for differences
The following method returns the difference between the two lists after applying the given function to each element of the 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. Chained function call
The following methods 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.Check for duplicate values
The following method uses the fact that the set() method contains only unique elements to check whether the list has duplicate values.
def has_duplicates(lst):
return len(lst) != len(set(lst))
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False
19. Merge two dictionaries
The following method can be used to merge two dictionaries.
def merge_two_dicts(a, b):
c = a.copy() # make a copy of a
c.update(b) # modify keys and values of a with the ones from b
return c
a = { x : 1, y : 2}
b = { y : 3, z : 4}
print(merge_two_dicts(a, b)) # { y : 3, x : 1, z : 4}
In Python 3.5 and later, you can also perform the following operations:
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}
20. Convert two lists into a dictionary
The following method can convert two lists into one dictionary.
def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # { a : 2, c : 4, b : 3}
21. Use enum
The following method takes a dictionary as input, and then returns only the keys in that dictionary.
list = ["a", "b", "c", "d"]
for index, element in enumerate(list):
print("Value", element, "Index ", index, )
# ( Value , a , Index , 0)
# ( Value , b , Index , 1)
#( Value , c , Index , 2)
# ( Value , d , Index , 3)
22. Calculate the time required
The following code snippet can be used to calculate the time required to execute a specific code.
import time
start_time = time.time()
a = 1
b = 2
c = a + b
print(c) #3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)
# ( Time: , 1.1205673217773438e-05)
23.Try else instruction
You can use the else clause as part of the try/except block, and if no exception is thrown, the clause is executed.
try:
2*3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")
#Thank God, no exceptions were raised.
24. Find the most common elements
The following method returns the most common elements that appear 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)
25. Palindrome
The following method can check whether the given string is a palindrome. This method first converts the string to lowercase and then removes non-alphanumeric characters from it. Finally, it compares the new string with the reversed version.
def palindrome(string):
from re import sub
s = sub( [W_] , , string.lower())
return s == s[::-1]
palindrome( taco cat ) # True
26. Simple calculator without if-else statement
The following code snippet will show how to write a simple calculator that does not use if-else conditions.
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action[ - ](50, 25)) # 25
27. Disorder the order of elements
The following algorithm randomly shuffles the order of the elements in the list by implementing the Fisher-Yates algorithm to sort 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]
28. List flattening
The following method can flatten the list, similar to [].concat(...arr) in JavaScript.
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]
29. Variable Exchange
The following is a quick way to swap two variables without using additional variables.
def swap(a, b):
return b, a
a, b = -1, 14
swap(a, b) # (14, -1)
30. Get the default value of the missing key
The following code snippet shows how to get the default value when the key to find is not included in the dictionary.
d = { a : 1, b : 2}
print(d.get( c , 3)) # 3
The above is a short list of useful methods you may find in your daily work. It is mainly based on this GitHub project (https://github.com/30-seconds/30_seconds_of_knowledge), where you can find many other useful code snippets, including Python and other programming languages and technologies.
Author: Fatos Morina (https://towardsdatascience.com/@FatosMorina)
Data Scientist | Software Engineer | Author
Personal homepage: https://www.fatosmorina.com/
via https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172
Recommended reading