Open13

Python Tips

BlueSilverCatBlueSilverCat

Pylint

E1101: 'Instance of .. has no .. member'

--extension-pkg-allow-list=cv2
or
--generated-members=cv2.+

BlueSilverCatBlueSilverCat

多重ループからのbreak

使う機会がなかったので知らなかった。
覚えてないだけかな

for i in range(10):
  for j in range(10):
    if j == 3:
      break
  else:
    continue
  break
BlueSilverCatBlueSilverCat

escape sequence

\newlineは、以下のような意味。

"""\
abc
"""

print("a\
b")

バイナリデータを扱っていたら混乱したので復習

c = "A"
h = "\x41"
o = "\101"
n = "\N{LATIN CAPITAL LETTER A}"
u = "\u0041"
U = "\U00000041"
print(c, h, o, n, u, U) #すべて同じ文字を表す

cb = b"A"
hb = b"\x41"
ob = b"\101"
ub = b"\u0041" #エスケープシーケンスと扱われない
Ub = b"\U00000041" #エスケープシーケンスと扱われない

print(cb, hb, ob, ub, Ub)
print(cb.decode("utf-8"), hb.decode("utf-8"), ob.decode("utf-8"))
print(ub.decode("utf-8"), Ub.decode("utf-8"))
BlueSilverCatBlueSilverCat

raw文字列について

何度か遭遇しているはずだが、メモに残しておく

r"\" # SyntaxError
BlueSilverCatBlueSilverCat

ソート

from operator import itemgetter

d = [
  {
    "kind": "cat",
    "number": 1
  },
  {
    "kind": "dog",
    "number": 2
  },
  {
    "kind": "dog",
    "number": 1
  },
  {
    "kind": "cat",
    "number": 2
  },
]

r = sorted(d, key=lambda x: (x["number"], x["kind"]))
print(r)
r = sorted(d, key=itemgetter(1, 2))
print(r)
BlueSilverCatBlueSilverCat

update

windows
pip3 install --upgrade ((pip3 freeze) -replace '==.+','')
pip install pip-review
pip-review --local --auto
BlueSilverCatBlueSilverCat

Numpy

vectorize

otypeを渡さないと1つ目の要素を2回呼び出す。
vectorizeする関数が破壊的な動作をする場合は、意図した動作をしない可能性がある。
otypeは、必ず渡す。

def fun1(e):
  print(f"fun1: {e}")
  return e % 2

array = np.array([1, 2, 3, 4, 5])
vfunc = np.vectorize(fun1)
result = vfunc(array, x=1)
print(result)
fun1: 1
fun1: 1
fun1: 2
fun1: 3
fun1: 4
fun1: 5
[1 0 1 0 1]
vfunc = np.vectorize(fun1, otypes=[int])
result = vfunc(array)
print(result)
fun1: 1
fun1: 2
fun1: 3
fun1: 4
fun1: 5
[1 0 1 0 1]
def fun2(e, x):
  print(f"fun2 {x}: {e}")
  return e % 2

vfunc = np.vectorize(fun2, otypes=[int])
# result = vfunc(array, 1)
result = vfunc(array, x=1)
print(result)
BlueSilverCatBlueSilverCat

package list

python.exe -m pip install --upgrade pip
pip install pyocr
pip install pillow
pip install opencv-python
pip install numpy
pip install googletrans
pip install pyperclip
pip install requests
pip install yapf
pip install pylint
pip install selenium
pip install bs4
pip install lxml
pip install pynput
pip install pyautoqui
pip install send2trash
BlueSilverCatBlueSilverCat

VSCode で "unable to import" error"

Python Interpreter を選ぶと解消するかも

BlueSilverCatBlueSilverCat

辞書にmapを適応してmapにする

辞書内包表記にすべき。

def toInt1(delta):
  for k, v in delta.items():
    delta[k] = int(v)

def toInt2(i):
  return (i[0], int(i[1]))

d = {
  "a": "1",
  "b": "2",
  "c": "3",
}
d1 = d.copy()
d2 = d.copy()

print(d1)
print(d2)

toInt1(d1)
d2 = dict(map(toInt2, d2.items()))
d3 = {k: int(v) for k, v in d.items()}

print(d1)
print(d2)
print(d3)