9 Essential Python Snippets to Optimize your Scripting Routine

https://miro.medium.com/max/1200/0*5SHdUcr798C43p7S

Original Source Here

1. Creating dictionaries with defaultdict and lambda functions

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 cool thing about defaultdicts is that they will never raise a KeyError. Any key that does not exist gets the value returned by the default factory, which in t his case is a lambda function that returns a default numpy array with 5 zeros for any key you give it.

2. Regex basic recipe

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 a lot of python pipelines so it is always helpful to remember the core regex recipe.

3. Getting the difference out of two lists using sets

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, sets facilitate getting the difference between two python lists both as a list as well as a set.

4. Partial functions

from functools import partialdef 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 but takes less arguments than the original so that you can use it to apply that argument to multiple different arguments.

5. Using the hasattr() built in method to get object attribute

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

6. Checking if a variable is of a given type with isinstance()

isinstance(1, int)
#Output
True

7. Printing numbers from a list using map()

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

A faster and more efficient way than for loops to print the contents of a list.

8. Formatting datetime dates with .join() method

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

9. Randomize two lists with the same rule

import numpy as npx = 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])

AI/ML

Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: