Nine practical Python skills let you write faster and better scripts!

Writing Python scripts to solve various small problems is one of my daily pleasures. I always like to find the python answer to a problem, and I also like to quickly find some great solutions in stack overflow when I don't know the solution.

In this article, I will share nine Python scripts that are often used in daily work.

1. Use the defaultdict and lambda functions to create a dictionary

from collections import defaultdict
import numpy as np
q = defaultdict(lambda: np.zeros(5))
# Example output
In [34]: q[0]
Out[34]: array([0., 0., 0., 0., 0.])

The coolest thing about defaultdicts is that they never raise KeyError. Any key that does not exist will get the value returned by the default factory. In this case, the default factory is a lambda function that returns a default NumPy array containing five zeros for any given key.

2. Basic formula of regular expression

import re
pattern = re.compile(r"\d\d")
print(re.search(pattern,"Let's find the number 23").group())
# or
print(re.findall(pattern, "Let's find the number 23"))[0]
# Outputs
'23'
'23'

Regex is a must for many python pipelines, so it's always helpful to remember the core regex methods.

3. Use the set to get the difference from the two lists

list1 = [1,2,3,4,5]
list2 = [3,4,5]
print(list(set(list1) — set(list2)))
# or
print(set(lista1).difference(set(lista2)))
# Outputs
[1,2]
{1,2}

Here, the collection helps to get the difference between two python lists, which are both a list and a collection.

4. partial function

from functools import partial
def multiply(x,y):
    return x*y
dbl = partial(multiply,2)
print(dbl)
print(dbl(4))
# Outputs

functools.partial(<function multiply at 0x7f16be9941f0>, 2)
8

Here, we create a function that copies another function, but uses fewer parameters than the original function, so you can use it to apply the parameter to multiple different parameters.

5. Use the built-in method of hasattr() to obtain the object attribute

class SomeClass:
    def __init__(self):
    self.attr1 = 10
    def attrfunction(self):
        print("Attreibute")
hasattr(SomeClass, "attrfunction")
# Output 
True

6. Use isinstance() to check whether the variable is of the given type

isinstance(1, int)
#Output
True

7. Print the numbers in the list using map()

list1 = [1,2,3]
list(map(print, list1))
# Output
1
2
3

A faster and more efficient method than looping through the contents of a list.

8. Use The join () method formats the datetime date

from datetime import datetime
date = datetime.now()
print("-".join([str(date.year), str(date.month), str(date.day)])
# Output
'2021-6-15'

9. Randomize two lists with the same rule

import numpy as np
x = np.arange(100)
y = np.arange(100,200,1)
idx = np.random.choice(np.arange(len(x)), 5, replace=False)
x_sample = x[idx]
y_sample = y[idx]
print(x_sample)
print(y_sample)
# Outputs
array([68, 87, 41, 16,  0])
array([168, 187, 141, 116, 100])

summary

This article aims to share some basic Python problems that may be encountered in the daily Python script workflow.

Technical exchange

Welcome to reprint and collect this article. It's not easy to code words. If you have something to gain, please praise and support it!

In order to facilitate learning and exchange, this number has opened a technical exchange group, which is added as follows:

Directly add the little assistant wechat: pythoner666, remarks: CSDN+python, or add it in the following way!

Keywords: Python Data Analysis list

Added by alexdoug on Sun, 30 Jan 2022 03:05:46 +0200