Last active
August 8, 2022 18:46
-
-
Save AtmaMani/02610bb32472c2ec233f8b54478daf60 to your computer and use it in GitHub Desktop.
Python shortcuts and optimizations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#flatten a list of list | |
extent = [[-84.28620418884404, 33.98540048952816], [-84.09769613557806, 34.090609514767856]] | |
flat_list = [element for sublist in extent for element in sublist] | |
# [-84.28620418884404, 33.98540048952816, -84.09769613557806, 34.090609514767856] | |
#stringify a list of numbers | |
stringified_flat_list = ','.join(str(e) for e in flat_list) | |
# '-84.28620418884404,33.98540048952816,-84.09769613557806,34.090609514767856' | |
# print fixed with tables | |
# use 'f{val:>num}' as shown below | |
>>> l = ['atma','mani','bharathi','suganya','baskaran','esha'] | |
>>>for i,e in enumerate(l): | |
print(f"{e:>13} : {i}") | |
""" prints | |
atma : 0 | |
mani : 1 | |
bharathi : 2 | |
suganya : 3 | |
baskaran : 4 | |
esha : 5 | |
""" | |
# jupyter notebook suppress warnings | |
import warnings; warnings.simplefilter('ignore') | |
# make a timestamp | |
from datetime import datetime | |
datetime.now().strftime("%y%h%d_%H%M%S") | |
# '21Oct04_225133' | |
# print large numbers with commas: | |
num = 1222 | |
print(f'{num:,d}') # will print 1,222 The `d` represents int | |
float_num = 1222.334433 | |
print(f'{float_num:,0.2f}') # will print 1,222.33 with 2 decimal places | |
# Decorator boiler plate | |
import functools | |
def do_twice(func): | |
@functools.wraps(func) # optional, preserves function's __name__ field | |
def wrapper_do_twice(*args, **kwargs): # optional to pass args, will send args to called func | |
func(*args, **kwargs) | |
return func(*args, **kwargs) # optional return statement, useful if called func returns value | |
return wrapper_do_twice | |
@do_twice | |
def some_function(args): | |
print("something") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment