- datetime
- Decode a numpy array of encoded literals/strings in Python3?
- Save an array containing strings to a txt file. Just use savetxt with fmt='%s'.
- Initialize a numpy array of NaN values: np.fill(shape, np.nan)
- Using NumPy Argmin or Argmax Along with a Conditional. See: http://seanlaw.github.io/2015/09/10/numpy-argmin-with-a-condition/
- Check the membership of a key in a dictionary: use "key in dic" returning True/False.
- In a bracket of defining a list, one can use loop: [I for i in range(10)].
One can even use double loop: [I*j for I in range(10) for j in range(10)]; Note that i is outer loop variable and j inner.
One can use if statement as well: [x if x%2==0 else 0 for x in range(5)].
If you don't need else above, then do like [x for x in range(5) if x%2==0], which produces [0,2,4]. - To get the path of the script running or its directory, "print(os.path.dirname(os.path.realpath(__file__)))" (sys.path[0], sys.argv[0])
- One can run python passing a command to execute, as "python -c "import numpy; print(numpy.__version__)""
- To check a file exists or not by its path, use os.path.exists() and os.path.isfile().
- To loop through all files in a directory, use "os.walk":

https://stackabuse.com/python-list-files-in-a-directory/ - To access entries of an OrderedDict object by index, go like "list(orderedDictObj.items())[idx]"; converting "items" to a list is needed.
- To get keys of a dictionary object, "dic.keys()".
- To run a (python) script in a python script, use "os.system()" or "subprocess.Popen()"; os.system('python script.py --parameter xxx'); if the executable is the same as the current python the user is running, os.system(sys.executable + ' script.py').
- Zero padding in python: https://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-a-string
- To have a bool-type argparse argument, do not use "type=bool", but use "action='store_true'"(or "'store_false'"); https://note.nkmk.me/python-argparse-bool/.
- https://stackoverflow.com/questions/28652976/passing-array-range-as-argument-to-a-function
- print a Numpy array without brackets?
>>> a = [1,2,3,4,5]>>> ' '.join(map(str, a))"1 2 3 4 5" - Measuring time of program execution(https://stackoverflow.com/questions/1557571/how-do-i-get-time-of-a-python-programs-execution):
- import timestart_time = time.time()main()print("--- %s seconds ---" % (time.time() - start_time))
- To ignore exception,try: something()except: pass
- Tuple object cannot be modified element wise. To do so, convert it once for list for example:
list_var = list(tuple_var)
https://www.tutorialspoint.com/How-we-can-update-a-Python-tuple-element-value - To write arbitrary objects to a file, use pickle package.
https://www.techcoil.com/blog/how-to-save-and-load-objects-to-and-from-file-in-python-via-facilities-from-the-pickle-module/ - To have a decimal-step sequence, use np.linspace(low_lim, upp_lim, num_points_inbetween)
- Some unexpected behavior of Python: https://en.wikipedia.org/wiki/Duck_typing
- python pickleでオブジェクトを保存するときに、RuntimeError: maximum recursion depth exceeded while pickling an objectが出る場合の対処import sys; sys.setrecursionlimit(10000)
- To check the memory size of a variable in python
sys.getsizeof(VARIABLE) - Singleton pattern
https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_singleton.htmclass Singleton: __instance = None @staticmethod def getInstance(): """ Static access method. """ if Singleton.__instance == None: Singleton() return Singleton.__instance def __init__(self): """ Virtually private constructor. """ if Singleton.__instance != None: raise Exception("This class is a singleton!") else: Singleton.__instance = self
No comments:
Post a Comment