12/17/2023 0 Comments Python code snippets""" count the occurrence of elements in a list from collections import CounterĬount = Counter()įlatten list of lists to a list ll = , List comprehension on a nested list? l =, ,, ,, ] Print(tuple(map(operator.sub, a, b))) # (-3, -1, 1, 3) list comprehension with if else Python element-wise tuple operations like sum import operator Print(max(l, key= lambda x : x)) # 'c' add two tuples element-wise Print(l2) # max among a list of tupleįind the maximum value in a list of tuples in Python l = Print(list(zip(l1, l2))) # convert list of tuples to two lists Index, value = max(enumerate(l), key=emgetter( 1)) # 4,9 from two list to a list of tuples Pythonic way to find maximum value and its index in a list? l = Python: take max N elements from some list import heapq Print(l) # get N largest values from a list # as opencv loads in BGR format by default, we want to show it in RGB. Plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) # load image using cv2.and do processing. Ipython.magic( "matplotlib qt5") # show up a window when drawing with matplotlib to show image in jupyter notebook import cv2 To use IPython magic in a script file from IPython import get_ipython Print(list(s)) # to check the layers of a hdf5 weight file import h5py How to convert a string to a list in Python? s = "abc" # 'abcdefghijklmnopqrstuvwxyz' string to list Python: how to print range a-z? import string Print(fname) # "a_b_c" string range from a to z Start = haystack.find(needle, start+len(needle)) Python | Ways to find nth occurrence of substring in a stringįind the nth occurrence of substring in a string def find_nth (haystack, needle, n): Return True find Nth occurrence of a substring in a string S.encode(encoding= 'utf-8').decode( 'ascii') Type(s) # to remove non-ascii characters from a string s = s.encode( 'ascii', errors= 'ignore').decode() With open( 'xxx.txt', 'w', encoding= 'utf-8') as f:į.writelines(map( lambda line : line+ '\n', lines))Ĭount substring in a string str = "hello, goodbye, and hello"īest way to convert string to bytes in Python 3? s = "12345" # myVar exists write list of strings to a file lines = To check if myVar is one of global variables: if 'myVar' in globals(): To check if myVar is one of local variables: if 'myVar' in locals(): Python3 UnicodeDecodeError with readlines() method with open(fname, 'w', errors= 'ignore') as f: Use utf-8-sig encoding so that the first line won't be prefixed with \ufeff with open( 'stop_words.txt', 'r', encoding= 'utf-8-sig', errors= 'ignore') as f: ( "hello") #INFO:root:hello read file with chinese in Windows Getting the class name of an instance? s = "x" Os.makedirs( "first_layer/second_layer", exist_ok= True) # this works even when 'first_layer' doesn't exist How can I safely create a nested directory? import os Os.path.splitext(os.path.basename(fname)) #'log' mkdir -p Os.path.splitext(fname) #'/xxx/yyy/zzz/log' How to get the filename without the extension from a path in Python? import os Os.path.basename(fname) #'log.txt' get file name without extension Get directory name & file name from full pathĮxtract a part of the filepath (a directory) in Python import os Print(sum(f.stat().st_size for f in root_directory.glob( '**/*') if f.is_file() )) Print(statinfo.st_size) # 26571 # the unit is byte check directory sizeĬalculating a directory's size using Python? from pathlib import Path Print(inspect.currentframe().f_name)Ĭlass dummy_class: def dummy_method (self):Ĭ.dummy_method() # dummy_method check file exist import os Hasattr(string, "lower") # False get current function nameĭetermine function name from within that function (without using traceback) import inspect How to know if an object has an attribute in Python import string Sys.getsizeof(s) #55 check object having attribute or not How to read user input until EOF? from sys import stdinĭetect python version inside python kernel import sys How to round to 2 decimals with Python? import math Print(os.path.dirname(os.path.realpath(_file_))) How can I find script's directory? import os How to make 'python' program command execute Python 3? vim ~/.bash_aliases # add "alias python=python3" source ~/.bash_aliases
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |