Share 30 Python tips

Posted by muppet on Fri, 19 Nov 2021 02:11:22 +0100

Python is one of the most popular languages at present. It is widely used in data science and machine learning, network development, scripting, automation and so on.

There are two reasons for the popularity:

  • Simple, elegant and concise, no nonsense code
  • Easy to learn, quick to start, friendly to novices

Next, let's share 30 short python codes and feel how to quickly complete interesting tasks in 30 seconds or less. Welcome to collect, pay attention, like and support!

"How can I know if I'm not hurt by java?" 🤪. There are some principles that you must try in person before you know. For example, what is meant by "life is short, I use Python ~".

1. The list value is unique

Use the set() conversion function to determine whether there are duplicate elements in 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]
print(all_unique(x)) # False
print(all_unique(y)) # True

2. Deformation words

Judge whether two strings are anamorphic words. Anamorphic words mean that after rearranging the letters, the two strings can be equal. In essence, each character appears the same number of times.

from collections import Counter

def anagram(first, second):
    return Counter(first) == Counter(second)


anagram("abcd3", "3acdb") # True

3. Memory view

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 string N times

The following code quickly prints a string N times without using a loop.

n = 2
s ="Programming"

print(s * n) # ProgrammingProgramming

6. Initial capitalization

Simply use 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 blocking

The following method divides a list into small lists of a specified size.

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

print(chunk([1, 2, 3, 4, 5, 6],2))
# [[1, 2], [3, 4], [5, 6]]

print(chunk([1, 2, 3, 4, 5, 6, 7],2))
# [[1, 2], [3, 4], [5, 6], [7]]

8. filter fast filtering

Use the filter() method to filter "false" values (False, None, 0, and "") from the list

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

9. Array transpose

Skillfully transpose a two-dimensional array with zip().

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(list(transposed))
# [('a', 'c', 'e'), ('b', 'd', 'f')]

array = [['a', 'b', 'c'], ['d', 'e', 'f']]
transposed = zip(*array)
print(list(transposed))
# [('a', 'd'), ('b', 'e'), ('c', 'f')]

10. Chain comparison

You can make multiple comparisons with various operators in one line, and the magic method is natural.

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

11. join() link

Use join() to change the string list into a single string, and each element in the list is separated by commas.

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

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

12. Get vowels

The following code gets the vowel ('a ',' e ',' I ',' o ',' U ') letters in the string.

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


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

13. De initialisation

Turns the first letter of the string to lowercase.

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

14. Flat list

The following method uses recursion to flatten a potential deep list.

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


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

15. List difference

The following method simulates a set of lists to quickly calculate the difference.

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. Difference function

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. Chain function

You can call multiple functions on 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

Use the feature that set() only contains unique elements to judge 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]
print(has_duplicates(x)) # True
print(has_duplicates(y)) # False

19. Merge Dictionaries

The following method uses update() to merge the 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 above, you can be more elegant:

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. Turn two lists into Dictionaries

The following method uses the zip() and dict() functions to convert the two lists into a 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. Skillfully use enumerate

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. Time consuming statistics

Use time.time() to calculate the time required to execute a piece of 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

else clause is a part of the try/except block. 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. High frequency discovery

The following 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]
print(most_frequent(numbers))
# 2
  

25. Palindrome judgment

Checks whether the given string is a palindrome.

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


print(palindrome('mom')) # True
print(palindrome('pythontip')) # False

26. Simple calculator

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. Random shuffle

Randomize the order of elements in a list with random.shuffle(). Note 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 expansion

Similar to []. concat(...arr) in JavaScript, flatten a list. Note that the following code cannot flatten deeply nested lists.

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


print(spread([1,2,3,[4,5,6],[7],8,9]))
# [1,2,3,4,5,6,7,8,9]
print(spread([1,2,3,[4,5,6],[7],8,9,[10,[11]]]))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, [11]]

29. Variable exchange

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. Dictionary default

Use dict.get(key,default) to return the default value when the key to be found does not exist in the dictionary.

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

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

Section

The 30 interesting python codes shared above hope to be useful to you.

If you think it's OK, praise the collection, and a good man will live a safe life.

pythontip Happy Coding!

Official account: quark programming

Add vx: pythontip, talk about Python

Topics: Python