Collect it quickly so that you can use the 30 Python tips for taking off

Python is one of the most popular languages. Many people use it in data science and machine learning, Web development, scripting, automation and other fields.

This popularity is partly due to its simplicity and ease of learning.

In this article, I will introduce you to 30 short and practical Python techniques. There are many contents. It is recommended to collect and learn, like praise support, and provide a technical exchange group at the end of the article.

1. All unique

The following method checks whether there are duplicate elements in a given list. It uses the attribute of set() to delete 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. Crossword puzzles

This method can be used to check whether two strings are puzzles. A word puzzle is a word or phrase formed by rearranging the letters of different words or phrases, usually using all the original letters only once.

from collections import Counter

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)) # 24

4. Byte size

This method returns the length of a string in bytes.

def byte_size(string):
    return(len(string.encode('utf-8')))
    
    
byte_size('😀') # 4
byte_size('Hello World') # 11   

5. Print a string N times

This code snippet can be used to print a string n times without using a loop to do so.

n = 2
s ="Programming"

print(s * n) # ProgrammingProgramming

6. Initial capitalization

This snippet uses only the title() method to capitalize the first letter of each word in the string.

s = "programming is awesome"

print(s.title()) # Programming Is Awesome

7. List cutting

This method divides the list into smaller lists of the specified size.

def chunk(list, size):
    return [list[i:i+size] for i in range(0,len(list), size)]

8. Delete false values

This method uses filter() to remove False values (False, None, 0, and '') from the list

def compact(lst):
    return list(filter(None, lst))
  
  
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]

9. Transpose two-dimensional array

This code snippet can be used to transpose 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

You can compare various operators multiple times in a row.

a = 3
print( 2 < a < 8) # True
print(1 == a < 2) # False

11. Comma separated

This code snippet can be used to convert a list of strings into a single string, with each element in the list separated by commas.

hobbies = ["basketball", "football", "swimming"]

print("My hobbies are:") # My hobbies are:
print(", ".join(hobbies)) # basketball, football, swimming

12. Get vowels

This method gets the vowels in the string ('a ',' e ',' i ',' o ',' u ')

def get_vowels(string):
    return [each for each in string if each in 'aeiou'] 


get_vowels('foobar') # ['o', 'o', 'a']
get_vowels('gym') # []

13. Conversion

This method can be used to convert the first letter of a given string to lowercase.

def decapitalize(str):
    return str[:1].lower() + str[1:]
  
  
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar') # 'fooBar'

14. Flattening

The following method uses recursion to flatten potential deep lists.

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

def deep_flatten(xs):
    flat_list = []
    [flat_list.extend(deep_flatten(x)) for x in xs] if isinstance(xs, list) else flat_list.append(xs)
    return flat_list


deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]

15. Differences

This method finds the difference between two iterations by retaining only the value in the first one.

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. Differentiation

After applying the given function to each element of two lists, the following method returns the difference between 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

You 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. Duplicate value

The following method checks whether the list has duplicate values by using the fact that set() contains only unique elements.

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 methods 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 do the following:

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 Dictionaries

The following methods can be used to convert two lists into dictionaries

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 enumeration

This code snippet shows that you can use enumerate to get the value and index of the list.

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 spent

This code snippet can be used to calculate the time required to execute 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

You can use the else clause as part of a try/except block that will execute if no exception is thrown.

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. Statistics are most frequent

This method returns the most frequent element in the list.

def most_frequent(list):
    return max(set(list), key = list.count)
  

numbers = [1,2,1,2,3,2,1,4,2]
most_frequent(numbers)  

25. Palindrome

This method checks whether the given string is a palindrome.

def palindrome(a):
    return a == a[::-1]


palindrome('mom') # True

26. Calculator without if else

The following code snippet shows how to write a simple calculator without using the if else condition.

import operator
action = {
    "+": operator.add,
    "-": operator.sub,
    "/": operator.truediv,
    "*": operator.mul,
    "**": pow
}
print(action['-'](50, 25)) # 25

27.shuffle

This code snippet can be used to randomize the order of elements in the list. Notice that shuffle works in place and returns None.

from random import shuffle

foo = [1, 2, 3, 4]
shuffle(foo) 
print(foo) # [1, 4, 3, 2] , foo = [1, 2, 3, 4]

28. List flattening

This method is similar to []. concat(... arr) in JavaScript to flatten the list.

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. Exchange value

This is a very fast way to exchange two variables without using additional variables.

a, b = -1, 14
a, b = b, a

print(a) # 14
print(b) # -1

30. Get the default value of the missing key

This code snippet shows how to get the default value if the dictionary does not contain the key you want to find.

d = {'a': 1, 'b': 2}

print(d.get('c', 3)) # 3

Technical exchange

Welcome to reprint, collect, gain, praise and support!

At present, a technical exchange group has been opened, with more than 2000 group friends. The best way to add notes is: source + Interest direction, which is convenient to find like-minded friends

  • Method ① send the following pictures to wechat, long press identification, and the background replies: add group;
  • Mode ②. Add micro signal: dkl88191, remarks: from CSDN
  • WeChat search official account: Python learning and data mining, background reply: add group

Tags: Python Data Analysis

Posted on Sat, 27 Nov 2021 22:26:06 -0500 by saeed42