python

division //

if any of the number is float, the result will be float need int() conversion to get int. (How is it done?)

defaultdict vs setdefault

setdefault is a bad name, the accurate name should be ‘get_or_set’

key = "list_a"
dict.setdefault(key, []).append('element')

For defaultdicts, merely check whether a key exists unexpectedly creates the key.

how does a defaultdict interact with .get()? Safe, it doesn’t creates a new value.

2D array or tuple key?

  • sparse index -> tuple key

enumerate(items, start=1)

Use the start argument to control the start index of the enumeration change from 0 index to 1 index

items = ['a', 'b', 'c']
for index, item in enumerate(items, 1):
    print(index, item)
1 a
2 b
3 c

split()

  • what is the default behaviour of split()?
  • split(’ ‘) vs split()

raw-f-string

rf"" 需要注意什麼?

error: externally-managed-environment

python -m venv myenv
source myenv/bin/activate

note:

use myenv/bin/{executable} (e.g. myenv/bin/pip)

don’t change the folder path after creating the virtual env

Conda

conda create --name myenv python=3.X
conda activate myenv
conda env list

zip(*[…])

  • auto crop to the length of the shortest list

use zip as sliding window

for first, second, third in zip(string, string[1:], string[2:]): print(first + second + third)

🌐Check out other language versions!
Built with Hugo
Theme Stack designed by Jimmy