WTF Python!ð±ïŒPythonããŸãããïŒïŒåŸç·š
以äžã®æç« ã¯ãã¡ãã®ããŒãžã翻蚳ãããã®ã§ããïŒåŸç·šïŒ
https://github.com/satwikkansal/wtfpython
ãã¡ãã®GitHubãããžã§ã¯ããWhat the f*ck Python! ð±ãã¯ãäºæ³å€ã®ã³ãŒãã¹ãããããéããŠPythonãæ¢æ±ããç解ããããšãç®æããŠããŸããå€ãã®èšèªã«ç¿»èš³ãããŠããããŠã§ããµã€ããããŒãããã¯ãã³ãã³ãã©ã€ã³ããŒã«ãéããŠã€ã³ã¿ã©ã¯ãã£ãã«åŠã¶ããšãã§ããŸãã
ä»ã®ã¢ãŒã: Interactive Website | Interactive Notebook | CLI
Pythonã¯é«æ°Žæºãªè§£éåã®ããã°ã©ãã³ã°èšèªã§ãããéçºè ãå¿«é©ã«å©çšããããã«å€ãã®æ©èœãæèŒããŠããŸããããããäžèŠããã ãã§ã¯ç解ãé£ãPythonã¹ããããã®çµæãšããã®ããããŸãã
ãã¡ãã®ã¯ã¯ã¯ã¯ãããããžã§ã¯ãã§ã¯ãçŽæã«åããã¹ãããããPythonã®ããŸãç¥ãããŠããªãç¹åŸŽã®èåŸã«ããæ£ç¢ºãªã¡ã«ããºã ã®è§£èª¬ãè©Šã¿ãŸãããããŸã§é©ããã®ã§ã¯ãªããããªäŸãåãäžããããŠãããããããŸããããPythonã®é¢çœããšãããç解ããããããŠãããŸãããã®ãããžã§ã¯ãã¯ããã°ã©ãã³ã°èšèªã®å¥¥æ·±ããåŠã¶è¯ãæ段ã§ããèªè ã§ããããªãã«ãšã£ãŠãèå³æ·±ããã®ã«ãªãã§ãããã
çµéšè±å¯ãªPythonããã°ã©ããŒã®æ¹ã¯ãäžçºã§æ£è§£ãåãããããè©Šããã ãããããã€ãã®äºè±¡ã¯ä»¥åã«çµéšãããŠãããããããŸãããå€ãèšæ¶ãåŒã³æ»ãããšãã§ããã§ããããïŒ
P.S. ãã®èšäºãèªãã®ãäºåºŠç®ä»¥éã ãšããæ¹ã¯ãææ°çã€ããŠã¯ãã¡ããã芧ãã ããïŒææ°ã®æ¹èšã§è¿œå ãããäŸã«ã¯ã¢ã¹ã¿ãªã¹ã¯ãä»ããŠããŸãïŒã
ããã§ã¯ãå§ããŸããã...
ç®æ¬¡
- äŸã®æ§é
- 䜿ãæ¹
- å®äŸ
- ã»ã¯ã·ã§ã³: è³ãã¬ãã£ã¬ã³ãžïŒ
- ãŸãã¯å€§äºãªããšããïŒ
- ãã£ãããªæåå
- é£éããæäœã«ã¯æ³šæãå¿ èŠ
- **
is
**æŒç®åã®èœãšãç©Ž - ããã·ã¥ãã©ãŠããŒ
- æ¬è³ªçã«ã¯ã¿ããªåã
- 秩åºã®äžã®ç¡ç§©åº
- ãã©ã€ãç¶ãããïŒ
- äœã®ãããªã®ã
- è©äŸ¡æéã®äžäžèŽ
is not
ã¯is not
ã§ã¯ãªã- äžçºã§Xãåã€äžç®äžŠã¹ïŒ
- ã·ã¥ã¬ãŒãã£ã³ã¬ãŒã®å€æ°
- é¶ãå ãåµãå ã
- ãµãã¯ã©ã¹ã®ãªã¬ãŒã·ã§ã³
- ã¡ãœããã®ç䟡æ§ãšåäžæ§
- ãã¹ãŠçã§ãã
- é©ãã®ã³ã³ã
- æååãšããã¯ã¹ã©ãã·ã¥
not
ã®çµã³ç®- ååã®ããªãã«ã¯ã©ãŒãæåå
- ããŒã«å€ã®æå€ãªæå
- ã¯ã©ã¹å±æ§ãšã€ã³ã¹ã¿ã³ã¹å±æ§ã®éã
- Noneã®çæ
return
ããyield
- Nanååž°æ§
- äžå€ã®å€ç°
- å€éšã¹ã³ãŒãããæ¶ããå€æ°
- è¬ã®ããŒåå€æ
- ããã¯åããããªïŒ
- æŽæ°ã®æååå€æãéçãè¶ ãããšã
- ã»ã¯ã·ã§ã³: æ»ããããæé¢
- ã€ãã¬ãŒãäžã®èŸæžå€æŽåé¡
- ãã€ãã
del
æäœ - ã¹ã³ãŒãå€ã®å€æ°
- ã€ãã¬ãŒãäžã®ãªã¹ãé ç®åé€
- ã€ãã¬ãŒã¿ã®ããã·ãŒå§çž®
- ã«ãŒãå€æ°ãæŒããïŒ
- ããã©ã«ãã®å¯å€åŒæ°ã«æ³šæïŒ
- äŸå€åŠçã®èœãšãç©Ž
- åããªãã©ã³ããç°ãªãçµæïŒ
- ã¯ã©ã¹ã¹ã³ãŒããç¡èŠããåå解決
- ãéè¡å®¶ã®äžžãã
- èã®äžã®é
- Splitsies
- ã¯ã€ã«ãã€ã³ããŒã
- ãã¹ãŠsortedïŒ
- çå€äžã¯ååšããªãïŒ
- ã»ã¯ã·ã§ã³: é ãããå®ç©ãã¡ïŒ
- Pythonã空ãé£ã³ãããã ãã©âŠ
- ãªã
goto
ãªã®ã - ã«ãã³ã€ãããïŒ
- barryãããã
- Pythonã§ãç¥ã£ãŠããããšïŒæã¯è€é
- å®ã¯ååšãããã§ãïŒ
- Ellipsis
- ã€ã³ãããã£
- ãã³ã°ãªã³ã°ããã
- ã»ã¯ã·ã§ã³: èŠãç®ã«æãããããª
- è¡ãã¹ãããïŒ
- ãã¬ããŒãããŒã·ã§ã³
- äœãããããã...
- ã»ã¯ã·ã§ã³: ããŸããŸãªãããã¯
+=
ã®æ¹ãæ©ã- 巚倧ãªæååã®äœæ
dict
æ€çŽ¢ã®é 延- ã€ã³ã¹ã¿ã³ã¹
dict
ã®èšåŒµ - ãã®ä»ã®å°ããªçºèŠ
- ã»ã¯ã·ã§ã³: è³ãã¬ãã£ã¬ã³ãžïŒ
äŸã®æ§é
å šãŠã®äŸã¯ä»¥äžã®ãããªæ§é ã§è¡šç€ºãããŠããŸã:
ⶠé¢çœãã¿ã€ãã«
#ã³ãŒã
#é¢çœãããšãèµ·ããŸãã...
åºåïŒPythonã®ããŒãžã§ã³ïŒ
>>> ããªã¬ãŒãšãªãæ
äœããã®äºæž¬ã§ããªãåºå
ïŒå Žåã«ãã£ãŠã¯ïŒããã§äžèš
ð¡ 解説:
äœãèµ·ããŠããã®ãããªãèµ·ããŠããã®ãã®ç°¡åãªèª¬æã
#ã³ãŒã
#å¿
èŠããã°ã解説ã®ããã«äŸãè¿œå
åºåïŒPythonã®ããŒãžã§ã³ïŒ
>>> ããªã¬ãŒ # äœãèµ·ããŠããã®ããç°¡åã«ç解ããããã®äŸ
#ãæ£ããåºå
泚æïŒå šãŠã®äŸã¯Python 3.5.2ã®å¯Ÿè©±åã€ã³ã¿ãŒããªã¿ã§ãã¹ããããŠãããåºåã®åã«ç¹ã«æå®ããªãéããå šãŠã®PythonããŒãžã§ã³ã§åäœããã¯ãã§ãã
䜿ãæ¹
äœè ã®èãããããããã®äŸãæ倧éã«æŽ»çšããããã®æ¹æ³ã§ãã
-
äŸã®æåã®ã³ãŒãã泚ææ·±ãèªãã§ãã ãããçµéšè±å¯ãªPythonããã°ã©ããŒã§ããã°ãã»ãšãã©ã®å Žåã次ã«äœãèµ·ããããäºæž¬ã§ããã§ãããã
-
åºåã¹ãããããèªã¿ã
- ããªããæåŸ ãããã®ãšåããã©ãããã確èªãã ããã
- ãã®ãããªç¶æ
ã«ãªã£ãŠããçç±ãæ£ç¢ºã«ç解ã§ããŠããŸããïŒ
- çãããããããã§ããã°ïŒå šãåé¡ãããŸããïŒãæ·±åŒåžãããŠã解説ãèªãã§ãã ããã
- çãããã¯ããã§ããã°ãèªåã®ããšãè€ããäžã§ã次ã®äŸã«é²ãã§ãã ããã
P.S.ïŒã³ãã³ãã©ã€ã³ã䜿çšããŠWTFPythonãèªãããšãã§ããŸããpypi packageã䜿çšããŠã
$ pip install wtfpython -U $ wtfpython
ð äŸ
ã»ã¯ã·ã§ã³: æ»ããããæé¢
ⶠã€ãã¬ãŒãäžã®èŸæžã®å€æŽ
x = {0: None}
for i in x:
del x[i]
x[i+1] = None
print(i)
åºå (Python 2.7- Python 3.5):
0
1
2
3
4
5
6
7
ã¯ããã¡ããã©8å å®è¡ãããŠåæ¢ããŠããŸãã
ð¡ 解説:
- åæã«ç·šéããèŸæžã®ã€ãã¬ãŒã·ã§ã³ã¯ãµããŒããããŠããŸããã
- 8åå®è¡ãããã®ã¯ããã®æç¹ã§èŸæžããªãµã€ãºãããŠããå€ãã®ããŒãä¿æããããã§ãïŒ8ã€ã®åé€ãšã³ããªãããã®ã§ããªãµã€ãºãå¿ èŠã§ãïŒãããã¯å®éã«ã¯å®è£ ã®è©³çŽ°ã§ãã
- åé€ãããããŒãã©ã®ããã«æ±ããããªãµã€ãºããã€çºçãããã¯ãPythonã®å®è£ ã«ãã£ãŠç°ãªãå ŽåããããŸãã
- Python 2.7 - Python 3.5以å€ã®ããŒãžã§ã³ã§ã¯ã8åãšã¯ç°ãªãåæ°ã«ãªããããããŸãããïŒãã®æ°ãå®è¡ã®ãã³ã«å€ããããšã¯ãããŸããïŒãããã«ã€ããŠã®è°è«ã¯ãã¡ãããã® StackOverflowã¹ã¬ããããåç §ãã ããã
- Python 3.7.6以éã§ã¯ããããè©Šã¿ããš
RuntimeError: dictionary keys changed during iteration
äŸå€ãçºçããŸãã
del
æäœ
ⶠãã€ãã class SomeClass:
def __del__(self):
print("Deleted!")
åºå:
1.
>>> x = SomeClass()
>>> y = x
>>> del x # ãã㯠"Deleted!" ãåºåããã¯ãã§ã
>>> del y
Deleted
ããããåé€ãããŸãããæåã®è©Šã¿ã§ x
ãåé€ãããšãã« __del__
ãåŒã°ããªãã£ãçç±ã¯æšæž¬ã§ããŸãããïŒãã®äŸã«ãã£ãšã²ãããå ããŸãããã
>>> x = SomeClass()
>>> y = x
>>> del x
>>> y # y ãååšããã確èªããŸã
<__main__.SomeClass instance at 0x7f98a1a67fc8>
>>> del y # ããã "Deleted!" ãåºåããã¯ãã§ã
>>> globals() # ãã£ãšãã§ã¯ãã°ããŒãã«å€æ°ããã¹ãŠç¢ºèªããŠã¿ãŸããã
Deleted!
{'__builtins__': <module '__builtin__' (built-in)>, 'SomeClass': <class __main__.SomeClass at 0x7f98a1a5f668>, '__package__': None, '__name__': '__main__', '__doc__': None}
ã¯ããåé€ãããŸãã ð
ð¡ 解説:
del x
ã¯çŽæ¥x.__del__()
ãåŒã³åºããŸãããdel x
ã«ééãããšãPythonã¯ååx
ãçŸåšã®ã¹ã³ãŒãããåé€ããåç §ãããŠãããªããžã§ã¯ãx
ã®åç §ã«ãŠã³ãã1æžãããŸãã__del__()
ã¯ãªããžã§ã¯ãã®åç §ã«ãŠã³ãããŒãã«ãªã£ããšãã«ã®ã¿åŒã°ããŸãã- 第äºã®åºåã¹ããããã§ã
__del__()
ãåŒã°ããªãã£ãã®ã¯ã察話åã€ã³ã¿ããªã¿ã§ã®åã®æ (>>> y
) ãåããªããžã§ã¯ããžã®å¥ã®åç §ãäœæããããã§ãïŒå ·äœçã«ã¯ãREPLã§æåŸã®None
以å€ã®åŒã®çµæãåç §ãã_
ããžãã¯å€æ°ãããã«è©²åœããŸãïŒããã®ãããdel y
ã«ééãããšãã«åç §ã«ãŠã³ãããŒãã«ãªãã®ãé²ãã§ããŸããã globals
ïŒãŸãã¯éNone
ã®çµæã«ãªãäœãïŒãåŒã³åºãããšã§ã_
ãæ°ããçµæãåç §ããããã«ãªããæ¢åã®åç §ãåé€ãããŸãããããã§åç §ã«ãŠã³ãã0ã«ãªãã"Deleted!" ãåºåãããã®ãèŠãããšãã§ããŸãïŒã€ãã«ïŒïŒã
ⶠã¹ã³ãŒãå€ã®å€æ°
a = 1
def some_func():
return a
def another_func():
a += 1
return a
def some_closure_func():
a = 1
def some_inner_func():
return a
return some_inner_func()
def another_closure_func():
a = 1
def another_inner_func():
a += 1
return a
return another_inner_func()
åºå:
>>> some_func()
1
>>> another_func()
UnboundLocalError: local variable 'a' referenced before assignment
>>> some_closure_func()
1
>>> another_closure_func()
UnboundLocalError: local variable 'a' referenced before assignment
ð¡ 解説:
-
ã¹ã³ãŒãå ã«å€æ°ãå²ãåœãŠããšããã®ã¹ã³ãŒãã«ããŒã«ã«ãšãªããŸãããããã£ãŠã
another_func
ã®ã¹ã³ãŒãã§ã¯a
ãããŒã«ã«ã«ãªããŸãããåãã¹ã³ãŒãå ã§ä»¥åã«åæåãããŠããªãããããšã©ãŒãçºçããŸãã -
another_func
å ã§å€éšã¹ã³ãŒãã®å€æ°a
ãå€æŽããã«ã¯ãglobal
ããŒã¯ãŒãã䜿çšããå¿ èŠããããŸããdef another_func() global a a += 1 return a
åºå:
>>> another_func()
2
-
another_closure_func
ã®another_inner_func
ã®ã¹ã³ãŒãã§ã¯ãa
ãããŒã«ã«ã«ãªããŸãããåãã¹ã³ãŒãå ã§äºåã«åæåãããŠããªãããããšã©ãŒãçºçããŸãã -
another_inner_func
å ã§å€éšã¹ã³ãŒãã®å€æ°a
ãå€æŽããã«ã¯ãnonlocal
ããŒã¯ãŒãã䜿çšããŸããnonlocal
æã¯ãæãè¿ãå€éšã¹ã³ãŒãïŒã°ããŒãã«ãé€ãïŒã§å®çŸ©ãããå€æ°ãåç §ããããã«äœ¿çšãããŸããdef another_func(): a = 1 def another_inner_func(): nonlocal a a += 1 return a return another_inner_func()
åºå:
>>> another_func()
2
- ããŒã¯ãŒã
global
ãšnonlocal
ã¯ãPythonã€ã³ã¿ããªã¿ã«æ°ããå€æ°ã宣èšããã«ã察å¿ããå€éšã¹ã³ãŒãã§ããããæ¢ãããã«æ瀺ããŸãã - Pythonã§ã®åå空éãšã¹ã³ãŒã解決ãã©ã®ããã«æ©èœããããåŠã¶ããã«ã¯ããã¡ãã®ç°¡æœã®çŽ æŽãããã¬ã€ããã芧ãã ããã
ⶠã€ãã¬ãŒã·ã§ã³äžã®ãªã¹ãã®ã¢ã€ãã ã®åé€
list_1 = [1, 2, 3, 4]
list_2 = [1, 2, 3, 4]
list_3 = [1, 2, 3, 4]
list_4 = [1, 2, 3, 4]
for idx, item in enumerate(list_1):
del item
for idx, item in enumerate(list_2):
list_2.remove(item)
for idx, item in enumerate(list_3[:]):
list_3.remove(item)
for idx, item in enumerate(list_4):
list_4.pop(idx)
åºå:
>>> list_1
[1, 2, 3, 4]
>>> list_2
[2, 4]
>>> list_3
[]
>>> list_4
[2, 4]
åºåã [2, 4]
ã«ãªãçç±ã¯åãããŸãããïŒ
ð¡ 解説:
- ã€ãã¬ãŒãäžã®ãªããžã§ã¯ããå€æŽããã®ã¯è¯ããªãã§ããæ£ããæ¹æ³ã¯ããªããžã§ã¯ãã®ã³ããŒãã€ãã¬ãŒãããããšã§ãã
list_3[:]
ã¯ãŸãã«ãããè¡ããŸãã
>>> some_list = [1, 2, 3, 4]
>>> id(some_list)
139798789457608
>>> id(some_list[:]) # ã¹ã©ã€ã¹ããããªã¹ãã«å¯ŸããŠæ°ãããªããžã§ã¯ããäœæããããšã«çæã
139798779601192
del
ãremove
ãpop
ã®éã:
del var_name
ã¯ãvar_name
ã®ããŒã«ã«ãŸãã¯ã°ããŒãã«åå空éããã®ãã€ã³ãã£ã³ã°ãåé€ããŸãïŒãã®ããlist_1
ã¯åœ±é¿ãåããŸããïŒãremove
ã¯ç¹å®ã®ã€ã³ããã¯ã¹ã§ã¯ãªããæåã«äžèŽããå€ãåé€ããå€ãèŠã€ãããªãå Žåã¯ValueError
ãçºçãããŸããpop
ã¯ç¹å®ã®ã€ã³ããã¯ã¹ã®èŠçŽ ãåé€ããŠè¿ããç¡å¹ãªã€ã³ããã¯ã¹ãæå®ãããå Žåã¯IndexError
ãçºçãããŸãã
ãªãåºåã [2, 4]
ã«ãªãã®ãïŒ:
- ãªã¹ãã®ã€ãã¬ãŒã·ã§ã³ã¯ã€ã³ããã¯ã¹ããšã«è¡ããã
list_2
ãlist_4
ãã1
ãåé€ãããšããªã¹ãã®å 容ã¯[2, 3, 4]
ãšãªããŸããæ®ãã®èŠçŽ ã¯äžã«ã·ãããããŸããã€ãŸã2
ã¯ã€ã³ããã¯ã¹0ã«ã3
ã¯ã€ã³ããã¯ã¹1ã«ãªããŸãã次ã®ã€ãã¬ãŒã·ã§ã³ã¯ã€ã³ããã¯ã¹1ãèŠãããšã«ãªãã®ã§ïŒããã¯3
ã§ãïŒã2
ã¯å®å šã«ã¹ããããããŸãããªã¹ãã·ãŒã±ã³ã¹ã®ä»ã®ãã¹ãŠã®äº€äºèŠçŽ ã«å¯ŸããŠãåãããšãèµ·ãããŸãã - ã€ãã¬ãŒã·ã§ã³äžã«ãªã¹ãèŠçŽ ãåé€ãããšäœãèµ·ãããã説æããStackOverflowã®ã¹ã¬ããããåç §ãã ããã
- Pythonã®èŸæžã«é¢ããé¡äŒŒã®äŸã«ã€ããŠã¯ããã¡ãã®StackOverflowã®ã¹ã¬ãããåèã«ãªããŸãã
ⶠã€ãã¬ãŒã¿ã®ããã·ãŒå§çž®
>>> numbers = list(range(7))
>>> numbers
[0, 1, 2, 3, 4, 5, 6]
>>> first_three, remaining = numbers[:3], numbers[3:]
>>> first_three, remaining
([0, 1, 2], [3, 4, 5, 6])
>>> numbers_iter = iter(numbers)
>>> list(zip(numbers_iter, first_three))
[(0, 0), (1, 1), (2, 2)]
# ãããŸã§ã¯è¯ããæ®ãã¯ïŒ
>>> list(zip(numbers_iter, remaining))
[(4, 3), (5, 4), (6, 5)]
numbers
ãªã¹ãããèŠçŽ 3
ã¯ã©ãã«æ¶ããã®ã§ããããïŒ
ð¡ 解説:
-
Python ããã¥ã¡ã³ãã«ãã zip é¢æ°ã®æŠç¥çãªå®è£ ã¯ä»¥äžã®éãã§ãã
def zip(*iterables): sentinel = object() iterators = [iter(it) for it in iterables] while iterators: result = [] for it in iterators: elem = next(it, sentinel) if elem is sentinel: return result.append(elem) yield tuple(result)
-
ãããã£ãŠããã®é¢æ°ã¯ä»»æã®æ°ã®iterableãªããžã§ã¯ããåã蟌ã¿ããããã«å¯ŸããŠ
next
é¢æ°ãåŒã³åºããresult
ãªã¹ãã«åã¢ã€ãã ãè¿œå ããããããã®iterableãå°œãããšåæ¢ããŸãã -
ããã§ã®æ³šæç¹ã¯ãä»»æã®iterableãå°œããå Žåã
result
ãªã¹ãã®æ¢åã®èŠçŽ ãç Žæ£ãããããšã§ããnumbers_iter
ã®3
ã«ããããèµ·ããŸããã -
äžèšã®åŠçã
zip
ã䜿ã£ãŠæ£ããè¡ãæ¹æ³ã¯ä»¥äžã®éãã§ãã>>> numbers = list(range(7)) >>> numbers_iter = iter(numbers) >>> list(zip(first_three, numbers_iter)) [(0, 0), (1, 1), (2, 2)] >>> list(zip(remaining, numbers_iter)) [(3, 3), (4, 4), (5, 5), (6, 6)]
-
zipã®æåã®åŒæ°ã¯ãæãå°ãªãèŠçŽ ãæã€ãã®ã§ããã¹ãã§ãã
ⶠã«ãŒãå€æ°ãæŒããïŒ
for x in range(7):
if x == 6:
print(x, ': for x inside loop')
print(x, ': x in global')
åºå:
6 : for x inside loop
6 : x in global
x
ã¯forã«ãŒãã®ã¹ã³ãŒãã®å€ã§ã¯å®çŸ©ãããŠããŸããã§ããâŠ
# ä»åºŠã¯æåã«xãåæåããŠã¿ãŸã
x = -1
for x in range(7):
if x == 6:
print(x, ': for x inside loop')
print(x, ': x in global')
åºå:
6 : for x inside loop
6 : x in global
åºå (Python 2.x):
>>> x = 1
>>> print([x for x in range(5)])
[0, 1, 2, 3, 4]
>>> print(x)
4
åºå (Python 3.x):
>>> x = 1
>>> print([x for x in range(5)])
[0, 1, 2, 3, 4]
>>> print(x)
1
ð¡ 解説:
-
Pythonã§ã¯ãforã«ãŒãã¯ååšããã¹ã³ãŒãã䜿çšããå®çŸ©ãããã«ãŒãå€æ°ãåŸã«æ®ããŸããããã¯ãæ瀺çã«forã«ãŒãå€æ°ãã°ããŒãã«åå空éã§å®çŸ©ããå Žåã«ãé©çšãããŸãããã®å Žåãæ¢åã®å€æ°ã«åãã€ã³ãããŸãã
-
ãªã¹ãå å è¡šèšã®äŸã«ãããPython 2.xãšPython 3.xã®ã€ã³ã¿ãŒããªã¿ãŒã®åºåã®éãã¯ãWhatâs New In Python 3.0ã®å€æŽå±¥æŽã«ãŠè§£èª¬ãããŠããŸãã
"ãªã¹ãå å è¡šèšã¯ãã [... for var in item1, item2, ...] ã®æ§æ圢åŒããµããŒãããŠããŸããã代ããã« [... for var in (item1, item2, ...)] ãã䜿çšãã ããããŸãããªã¹ãå å è¡šèšã¯ç°ãªãã»ãã³ãã£ã¯ã¹ãæã£ãŠããããšã«ã泚æãã ãããlist() ã³ã³ã¹ãã©ã¯ã¿å ã®ãžã§ãã¬ãŒã¿åŒã«å¯Ÿããæ§æç³ã«è¿ããã®ã§ãç¹ã«ã«ãŒãå¶åŸ¡å€æ°ã¯ãã¯ãåšå²ã®ã¹ã³ãŒãã«ã¯æŒããŸããã"
ããã©ã«ãã®å¯å€åŒæ°ã«æ³šæïŒ
def some_func(default_arg=[]):
default_arg.append("some_string")
return default_arg
åºå:
>>> some_func()
['some_string']
>>> some_func()
['some_string', 'some_string']
>>> some_func([])
['some_string']
>>> some_func()
['some_string', 'some_string', 'some_string']
ð¡ 解説:
Pythoné¢æ°ã®ããã©ã«ãã®å¯å€åŒæ°ã¯ãé¢æ°ãåŒã³åºããã³ã«æ¬åœã«åæåãããããã§ã¯ãããŸããã代ããã«ãæè¿å²ãåœãŠãããå€ãããã©ã«ãå€ãšããŠäœ¿çšãããŸããæ瀺çã«[]ãsome_funcã«åŒæ°ãšããŠæž¡ããå Žåãdefault_argå€æ°ã®ããã©ã«ãå€ã¯äœ¿çšãããªããããé¢æ°ã¯æåŸ éãã®çµæãè¿ããŸãã
def some_func(default_arg=[]):
default_arg.append("some_string")
return default_arg
åºå:
>>> some_func.__defaults__ # ããã¯é¢æ°ã®ããã©ã«ãåŒæ°å€ã瀺ããŸã
([],)
>>> some_func()
>>> some_func.__defaults__
(['some_string'],)
>>> some_func()
>>> some_func.__defaults__
(['some_string', 'some_string'],)
>>> some_func([])
>>> some_func.__defaults__
(['some_string', 'some_string'],)
å¯å€åŒæ°ã«ãããã°ãé¿ããããã®äžè¬çãªæ¹æ³ã¯ãããã©ã«ãå€ãšããŠNoneãå²ãåœãŠãåŸã§ãã®åŒæ°ã«å¯ŸããŠå€ãé¢æ°ã«æž¡ããããã©ããããã§ãã¯ããããšã§ããäŸ:
def some_func(default_arg=None):
if default_arg is None:
default_arg = []
default_arg.append("some_string")
return default_arg
ⶠäŸå€åŠçã®èœãšãç©Ž
some_list = [1, 2, 3]
try:
# ãã㯠``IndexError`` ãçºçãããã¯ãã§ã
print(some_list[4])
except IndexError, ValueError:
print("Caught!")
try:
# ãã㯠``ValueError`` ãçºçãããã¯ãã§ã
some_list.remove(4)
except IndexError, ValueError:
print("Caught again!")
åºå (Python 2.x):
Caught!
ValueError: list.remove(x): x not in list
åºå (Python 3.x):
File "<input>", line 3
except IndexError, ValueError:
^
SyntaxError: invalid syntax
ð¡ 解説:
è€æ°ã®äŸå€ãexceptç¯ã«è¿œå ããã«ã¯ãæåã®åŒæ°ãšããŠäžžæ¬åŒ§ã§å²ã£ãã¿ãã«ãæž¡ãå¿ èŠããããŸãã2çªç®ã®åŒæ°ã¯ãªãã·ã§ã³ã§ãæäŸãããå Žåã«ã¯çºçããäŸå€ã€ã³ã¹ã¿ã³ã¹ã«ãã€ã³ããããŸããäŸã
some_list = [1, 2, 3]
try:
# ãã㯠``ValueError`` ãçºçãããã¯ãã§ã
some_list.remove(4)
except (IndexError, ValueError), e:
print("Caught again!")
print(e)
åºå (Python 2.x):
Caught again!
list.remove(x): x not in list
åºå (Python 3.x):
File "<input>", line 4
except (IndexError, ValueError), e:
^
IndentationError: unindent does not match any outer indentation level
äŸå€ãšå€æ°ãã³ã³ãã§åºåãããšã¯éæšå¥šã§ãããPython 3ã§ã¯æ©èœããŸãããæ£ããã¯as
ã䜿çšããŸããäŸã
some_list = [1, 2, 3]
try:
some_list.remove(4)
except (IndexError, ValueError) as e:
print("Caught again!")
print(e)
åºå
Caught again!
list.remove(x): x not in list
ⶠåããªãã©ã³ããç°ãªãçµæïŒ
a = [1, 2, 3, 4]
b = a
a = a + [5, 6, 7, 8]
åºå:
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4]
a = [1, 2, 3, 4]
b = a
a += [5, 6, 7, 8]
åºå:
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]
ð¡ 解説:
a += b
ã¯åžžã«a = a + b
ãšåãããã«ã¯åäœããŸãããã¯ã©ã¹ã¯op=
æŒç®åãç°ãªãæ¹æ³ã§å®è£ ããããšãã§ãããªã¹ãã¯ããããŸãã- åŒ
a = a + [5,6,7,8]
ã¯æ°ãããªã¹ããçæããa
ã®åç §ããã®æ°ãããªã¹ãã«èšå®ããŸãããb
ã¯å€æŽãããŸããã - åŒ
a += [5,6,7,8]
ã¯å®éã«ã¯ "extend" é¢æ°ã«ãããããããã®é¢æ°ã¯ãªã¹ãã«å¯ŸããŠæäœãããã®ã§ãa
ãšb
ã¯åããªã¹ããæãç¶ããŸããããã®ãªã¹ãã¯ãã®å Žã§å€æŽãããŸãã
ⶠã¯ã©ã¹ã¹ã³ãŒããç¡èŠããåå解決
x = 5
class SomeClass:
x = 17
y = (x for i in range(10))
åºå:
>>> list(SomeClass.y)[0]
5
x = 5
class SomeClass:
x = 17
y = [x for i in range(10)]
åºå (Python 2.x):
>>> SomeClass.y[0]
17
åºå (Python 3.x):
>>> SomeClass.y[0]
5
ð¡ 解説:
- ã¯ã©ã¹å®çŸ©å ã«ãã¹ããããã¹ã³ãŒãã¯ãã¯ã©ã¹ã¬ãã«ã§ãã€ã³ããããååãç¡èŠããŸãã
- ãžã§ãã¬ãŒã¿åŒã«ã¯ç¬èªã®ã¹ã³ãŒãããããŸãã
- Python 3.Xããããªã¹ãå å è¡šèšãç¬èªã®ã¹ã³ãŒããæã¡ãŸãã
ⶠãéè¡å®¶ã®äžžãã
ãªã¹ãã®äžå€®ã®èŠçŽ ãååŸããç°¡åãªé¢æ°ãå®è£ ããŠã¿ãŸãããïŒ
def get_middle(some_list):
mid_index = round(len(some_list) / 2)
return some_list[mid_index - 1]
Python 3.x:
>>> get_middle([1]) # ãã
1
>>> get_middle([1,2,3]) # ãã
2
>>> get_middle([1,2,3,4,5]) # ãïŒ
2
>>> len([1,2,3,4,5]) / 2 # ãã
2.5
>>> round(len([1,2,3,4,5]) / 2) # ãªãã§ïŒ
2
Pythonã«ãããš2.5ã®åæšäºå ¥ã¯2ã®ããã§ãã
ð¡ 解説:
- ããã¯æµ®åå°æ°ç¹ã®ç²ŸåºŠã®åé¡ã§ã¯ãªããæå³çãªæåãªã®ã§ããPython 3.0ããã
round()
ã¯éè¡å®¶ã®äžžãã䜿çšããŠããã0.5ã®ç«¯æ°ã¯æãè¿ãå¶æ°ã«äžžããããŸãïŒ
>>> round(0.5)
0
>>> round(1.5)
2
>>> round(2.5)
2
>>> import numpy # numpyãåãçµæãè¿ããŸã>>> numpy.round(0.5)
0.0
>>> numpy.round(1.5)
2.0
>>> numpy.round(2.5)
2.0
- ããã¯ãæ°å€ã®ç«¯æ°ãåæšäºå ¥ããéã«æšå¥šãããæ¹æ³ã§ãIEEE 754ã«ãèšèŒãããŠããŸãããã ããããã¯éåžžåŠæ ¡ã§æããããæ¹æ³ïŒãŒãããé¢ããæ¹åãžã®åæšäºå ¥ïŒãšã¯ç°ãªãããããéè¡å®¶ã®äžžããã¯ããŸãäžè¬çã§ã¯ãããŸãããå®éãå€ãã®äººæ°ã®ããã°ã©ãã³ã°èšèªïŒJavaScriptãJavaãC/C++ãRubyãRustãªã©ïŒã§ã¯ãéè¡å®¶ã®äžžããã¯äœ¿çšãããŠããŸããããã®ãããPythonç¬ç¹ã®ç¹åŸŽãšããŠã端æ°ã®åæšäºå ¥ã«é¢ããŠã®æ··ä¹±ãæãããšããããŸãã
- 詳ããã¯ãround()é¢æ°ã®ããã¥ã¡ã³ãããã®StackOverflowã®ã¹ã¬ããããåç §ãã ããã
get_middle([1])
ã1ãè¿ããã®ã¯ãã€ã³ããã¯ã¹ãround(0.5) - 1 = 0 - 1 = -1
ãšèšç®ããããªã¹ãã®æåŸã®èŠçŽ ãè¿ãããããã§ãã
ⶠèã®äžã®é
çµéšè±å¯ãªPythonããã°ã©ããŒã§ã以äžã®ã·ããªãªã®1ã€ä»¥äžã«ééããŠããªããšãã人ã¯äžäººãããªãã§ãããã
x, y = (0, 1) if True else None, None
åºå:
>>> x, y # (0, 1)ãæåŸ
ããã
((0, 1), None)
t = ('one', 'two')
for i in t:
print(i)
t = ('one')
for i in t:
print(i)
t = ()
print(t)
åºå:
one
two
o
n
e
tuple()
ten_words_list = [
"some",
"very",
"big",
"list",
"that"
"consists",
"of",
"exactly",
"ten",
"words"
]
åºå
>>> len(ten_words_list)
9
a = "python"
b = "javascript"
åºå:
# ã¢ãµãŒã·ã§ã³å€±æã¡ãã»ãŒãžãæã€assertæ
>>> assert(a == b, "Both languages are different")
# AssertionErrorã¯çºçããªã
some_list = [1, 2, 3]
some_dict = {
"key_1": 1,
"key_2": 2,
"key_3": 3
}
some_list = some_list.append(4)
some_dict = some_dict.update({"key_4": 4})
åºå:
>>> print(some_list)
None
>>> print(some_dict)
None
def some_recursive_func(a):
if a[0] == 0:
return
a[0] -= 1
some_recursive_func(a)
return a
def similar_recursive_func(a):
if a == 0:
return a
a -= 1
similar_recursive_func(a)
return a
åºå:
>>> some_recursive_func([5, 0])
[0, 0]
>>> similar_recursive_func(5)
4
ð¡ 解説:
-
1ã«ã€ããŠãæåŸ ãããåäœã®ããã®æ£ããæã¯
x, y = (0, 1) if True else (None, None)
ã§ãã -
2ã«ã€ããŠãæåŸ ãããåäœã®ããã®æ£ããæã¯
t = ('one',)
ãŸãã¯t = 'one',
ïŒã³ã³ããæããŠããŸãïŒãããã§ãªãå Žåãã€ã³ã¿ããªã¿ã¯t
ãstr
ãšã¿ãªããæåããšã«ã€ãã¬ãŒãããŸãã -
()
ã¯ç¹å¥ãªããŒã¯ã³ã§ã空ã®tuple
ãè¡šããŸãã -
3ã§ã¯ããããããã§ã«æ°ã¥ãããããšæããŸããããªã¹ãã®5çªç®ã®èŠçŽ ïŒ
"that"
ïŒã®åŸã«ã³ã³ããæããŠããŸãããã®ãããæé»ã®æååãªãã©ã«é£çµã«ãã£ãŠã>>> ten_words_list ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']
ãšãªããŸãã
4çªç®ã®ã¹ããããã§ã¯AssertionError
ã¯çºçããŸããã§ããããªããªããåã
ã®åŒa == b
ã䞻匵ããã®ã§ã¯ãªããå
šäœã®ã¿ãã«ã䞻匵ããŠããããã§ãã以äžã®ã¹ããããã ãšããã«åãããããã§ãããã
>>> a = "python"
>>> b = "javascript"
>>> assert a == b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert (a == b, "Values are not equal")
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
>>> assert a == b, "Values are not equal"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Values are not equal
- 5çªç®ã®ã¹ããããã«é¢ããŠã¯ã
list.append
ãdict.update
ãlist.sort
ãªã©ã®ããã«ã·ãŒã±ã³ã¹ããããã³ã°ãªããžã§ã¯ãã®ã¢ã€ãã ãå€æŽããã»ãšãã©ã®ã¡ãœããã¯ããªããžã§ã¯ãããã®å Žã§å€æŽããNone
ãè¿ããŸããããã®èåŸã«ããçç±ã¯ãæäœããã®å Žã§è¡ããå Žåã«ãªããžã§ã¯ãã®ã³ããŒãäœæããããšãªãããã©ãŒãã³ã¹ãåäžãããããã§ãïŒãã¡ãããåŒçšïŒã - æåŸã®äŸã¯æããã§ãããããå€æŽå¯èœãªãªããžã§ã¯ãïŒãªã¹ããªã©ïŒã¯é¢æ°å
ã§å€æŽå¯èœã§ãããã€ãã¥ãŒã¿ãã«ãªå代å
¥ïŒ
a -= 1
ïŒã¯å€ã®å€æŽã§ã¯ãããŸããã
ãããã®çŽ°ããç¹ã«æ°ãã€ããããšã§ãé·æçã«ãããã°ã®åŽåãå€§å¹ ã«ç¯çŽã§ããŸãã
ⶠSplitsies
>>> 'a'.split()
['a']
# 以äžãšåã
>>> 'a'.split(' ')
['a']
# ããã
>>> len(''.split())
0
# 以äžãšåãã§ã¯ãªã
>>> len(''.split(' '))
1
ð¡ 解説:
-
æåã¯ã
split
ã®ããã©ã«ãåºåãæåãåäžã¹ããŒã¹' '
ã§ãããšèãããããããŸããããããã¥ã¡ã³ãã«ãããšãsep ãæå®ãããŠããªãã None ã®å Žåãç°ãªãåå²ã¢ã«ãŽãªãºã ãé©çšãããŸããé£ç¶ãã空çœã¯åäžã®åºåãæåãšã¿ãªãããæååãå é ãŸãã¯æ«å°Ÿã«ç©ºçœãå«ãã§ããå Žåãçµæã«ã¯ç©ºã®æååãå«ãŸããŸããããã®ããã空ã®æååã空çœã®ã¿ãããªãæååã None ã§åå²ãããš [] ãè¿ãããŸãã
sep ãäžããããå Žåãé£ç¶ããåºåãæåã¯äžç·ã«ã°ã«ãŒãåãããã空ã®æååãåºåããã®ãšã¿ãªãããŸãïŒäŸãã°ã'1,,2'.split(',') 㯠['1', '', '2'] ãè¿ããŸãïŒãæå®ãããåºåãæåã§ç©ºã®æååãåå²ãããš [''] ãè¿ãããŸãã -
以äžã®äŸã§å é ãšæ«å°Ÿã®ç©ºçœãã©ã®ããã«æ±ããããã泚ææ·±ãèŠããšãããåãããããã§ãã
>>> ' a '.split(' ')
['', 'a', '']
>>> ' a '.split()
['a']
>>> ''.split(' ')
['']
ⶠã¯ã€ã«ãã€ã³ããŒã
# ãã¡ã€ã«: module.py
def some_weird_name_func_():
print("works!")
def _another_weird_name_func():
print("works!")
åºå
>>> from module import *
>>> some_weird_name_func_()
"works!"
>>> _another_weird_name_func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_another_weird_name_func' is not defined
ð¡ 解説:
-
ã¯ã€ã«ãã«ãŒãã€ã³ããŒãã䜿çšããªãããšã¯ããæšå¥šãããŸãããã®æãæçœãªçç±ã®äžã€ã¯ãã¯ã€ã«ãã«ãŒãã€ã³ããŒãã§ã¯ãã¢ã³ããŒã¹ã³ã¢ã§å§ãŸãååãã€ã³ããŒããããªãããšã§ããããã«ããã©ã³ã¿ã€ã äžã«ãšã©ãŒãçºçããå¯èœæ§ããããŸãã
-
from ... import a, b, c
ã®æ§æã䜿çšããŠããå Žåãäžèšã®NameError
ã¯çºçããŸããã§ããã>>> from module import some_weird_name_func_, _another_weird_name_func >>> _another_weird_name_func() works!
ã©ãããŠãã¯ã€ã«ãã«ãŒãã€ã³ããŒãã䜿çšãããå Žåã¯ã__all__
ãªã¹ããã¢ãžã¥ãŒã«å
ã§å®çŸ©ããå¿
èŠããããŸããããã¯ã¯ã€ã«ãã«ãŒãã€ã³ããŒããè¡ã£ãéã«å©çšå¯èœãšãªãå
¬éãªããžã§ã¯ãã®ãªã¹ããå«ããã®ã§ãã
__all__ = ['_another_weird_name_func']
def some_weird_name_func_():
print("works!")
def _another_weird_name_func():
print("works!")
åºå
>>> _another_weird_name_func()
"works!"
>>> some_weird_name_func_()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'some_weird_name_func_' is not defined
ⶠãã¹ãŠsortedïŒ
>>> x = 7, 8, 9>>> sorted(x) == x
False
>>> sorted(x) == sorted(x)
True
>>> y = reversed(x)
>>> sorted(y) == sorted(y)
False
ð¡ 解説:
sorted
ã¡ãœããã¯åžžã«ãªã¹ããè¿ãããªã¹ããšã¿ãã«ãæ¯èŒãããšPythonã§ã¯åžžã«False
ãè¿ããŸãã
>>> [] == tuple()
False
>>> x = 7, 8, 9
>>> type(x), type(sorted(x))
(tuple, list)
sorted
ãšã¯ç°ãªããreversed
ã¡ãœããã¯ã€ãã¬ãŒã¿ãè¿ããŸãããªããªãããœãŒãã«ã¯ã€ãã¬ãŒã¿ããã®å Žã§å€æŽããããè¿œå ã®ã³ã³ããïŒãªã¹ãïŒã䜿çšããå¿ èŠãããã®ã«å¯Ÿããéé ã«ã¯åã«æåŸã®ã€ã³ããã¯ã¹ããæåã®ã€ã³ããã¯ã¹ã«åãã£ãŠã€ãã¬ãŒãããã ãã§æžãããã§ãã- ãããã£ãŠ
sorted(y) == sorted(y)
ã®æ¯èŒã§ã¯ãæåã®sorted()
ã®åŒã³åºãã§ã€ãã¬ãŒã¿y
ãæ¶è²»ããã次ã®åŒã³åºãã§ã¯ç©ºã®ãªã¹ããè¿ãããŸãã
>>> x = 7, 8, 9
>>> y = reversed(x)
>>> sorted(y), sorted(y)
([7, 8, 9], [])
ⶠçå€äžã¯ååšããªãïŒ
from datetime import datetime
midnight = datetime(2018, 1, 1, 0, 0)
midnight_time = midnight.time()
noon = datetime(2018, 1, 1, 12, 0)
noon_time = noon.time()
if midnight_time:
print("Time at midnight is", midnight_time)
if noon_time:
print("Time at noon is", noon_time)
åºå (< 3.5):
('Time at noon is', datetime.time(12, 0))
çå€äžã®æéïŒTime at midnightïŒã衚瀺ãããŠããŸããã
ð¡ 解説:
Python 3.5ããåã§ã¯ãdatetime.time
ãªããžã§ã¯ããUTCã§çå€äžãè¡šããŠããå Žåããã®ããŒã«å€ã¯ False
ãšã¿ãªãããŠããŸãããif obj:
æ§æã䜿çšã㊠obj
ã None
ãŸãã¯ã空ãã®åçç©ãã©ããããã§ãã¯ããå Žåããšã©ãŒãçºçããããã§ãã
ã»ã¯ã·ã§ã³:é ãããå®ç©ãã¡ïŒ
ãã®ã»ã¯ã·ã§ã³ã§ã¯ãã»ãšãã©ã®åå¿è ãç¥ããªããPythonã«é¢ããèå³æ·±ãç¹åŸŽãåãäžããŠãããŸãã
ⶠPythonã空ãé£ã³ãããã ãã©âŠ
ã§ã¯ããããè©ŠããŠã¿ãŠãã ããã
import antigravity
åºå:
ããŒâŠç§å¯ã§ããã
ð¡ 解説:
antigravity
ã¢ãžã¥ãŒã«ã¯Pythonéçºè ã«ãã£ãŠãªãªãŒã¹ãããããã€ãã®ã€ãŒã¹ã¿ãŒãšãã°ã®å ã®äžã€ã§ããimport antigravity
ãå®è¡ãããšãPythonã«ã€ããŠã®ã¯ã©ã·ãã¯ãªXKCDã³ããã¯ã衚瀺ãããŠã§ããã©ãŠã¶ãéããŸãã- ããã ãã§ã¯ãããŸãããå®ã¯ãã€ãŒã¹ã¿ãŒãšãã°ã®äžã®å¥ã®ã€ãŒã¹ã¿ãŒãšãã°ããããŸããã³ãŒããèŠããšãXKCDã®ãžãªããã·ã³ã°ã¢ã«ãŽãªãºã ãå®è£ ãããšäž»åŒµããé¢æ°ãå®çŸ©ãããŠããŸãã
goto
ãã§ããªãïŒ
ⶠfrom goto import goto, label
for i in range(9):
for j in range(9):
for k in range(9):
print("I am trapped, please rescue!")
if k == 2:
goto .breakout # æ·±ããã¹ããããã«ãŒãããæãåºã
label .breakout
print("Freedom!")
åºå (Python 2.3):
I am trapped, please rescue!
I am trapped, please rescue!
Freedom!
ð¡ 解説:
goto
ã®åäœããããŒãžã§ã³ã¯ã2004幎4æ1æ¥ã®ãšã€ããªã«ããŒã«ã®ãžã§ãŒã¯ãšããŠçºè¡šãããŸããã- çŸåšã®PythonããŒãžã§ã³ã«ã¯ãã®ã¢ãžã¥ãŒã«ã¯å«ãŸããŠããŸããã
- åäœã¯ããŸããã䜿çšããªãã§ãã ãããPythonã«
goto
ããªãçç±ã¯ãã¡ãã
ⶠã«ãã³ã€ãããïŒ
Pythonã§ã¹ã³ãŒãã瀺ãããã«ç©ºçœã䜿ãã®ã奜ãã§ãªã人ã¯ã以äžãã€ã³ããŒãããããšã§Cèšèªã¹ã¿ã€ã«ã® {} ã䜿ãããšãã§ããŸãã
from __future__ import braces
åºå:
File "some_file.py", line 1
from __future__ import braces
SyntaxError: not a chance
ãããïŒãã¬ãŒã¹ã¯ïŒããšã倱æãããæ¹ã¯Javaãã䜿ããã ãããããŠãããäžã€é©ãã¹ãããšã§ããã__future__
ã¢ãžã¥ãŒã«ã®ã³ãŒãã«ãã㊠SyntaxError
ãã©ãã§çºçãããèŠã€ããããŸããïŒ
ð¡ 解説:
__future__
ã¢ãžã¥ãŒã«ã¯éåžžãPythonã®å°æ¥ã®ããŒãžã§ã³ããã®æ©èœãæäŸããããã«äœ¿çšãããŸãããããããã®ç¹å®ã®ã³ã³ããã¹ãã«ããã "future" ã¯ãç®èã§ãã- ããã¯ããã®åé¡ã«é¢ããã³ãã¥ããã£ã®ææ ã«é¢ããã€ãŒã¹ã¿ãŒãšãã°ã§ãã
- å®éã®ã³ãŒãã¯
future.c
ãã¡ã€ã«ã®ããã«ååšããŸãã - CPythonã³ã³ãã€ã©ã future ã¹ããŒãã¡ã³ãã«ééãããšãéåžžã®ã€ã³ããŒãã¹ããŒãã¡ã³ããšããŠæ±ãåã«
future.c
ã®é©åãªã³ãŒããæåã«å®è¡ããŸãã
ⶠBarryãããã
åºå (Python 3.x)
>>> from __future__ import barry_as_FLUFL
>>> "Ruby" != "Python" # ããã¯çãäœå°ããããŸãã
File "some_file.py", line 1
"Ruby" != "Python"
^
SyntaxError: invalid syntax
>>> "Ruby" <> "Python"
True
ããã§ã¯è¡ããŸãããã
ð¡ 解説:
-
ããã¯ã2009幎4æ1æ¥ã«çºè¡šãããPEP-401ã«é¢é£ããŠããŸãïŒä»ãªããã©ãããæå³ããåããã§ãããïŒã
-
PEP-401ããã®åŒçš
Python 3.0ã«ããã != äžçå·æŒç®åã¯ã²ã©ãééãã§ãããæã®çã¿ãèªçºãããã®ã§ãã£ãããšãèªèããããããFLUFL㯠<> ãã€ã¢ã¢ã³ãæŒç®åãå¯äžã®ç¶ŽããšããŠåå°å ¥ããã
-
Uncle Barryã¯PEPã§ããã«å€ãã®ããšãå ±æããŠããããã¡ãã§èªãããšãã§ããŸãã
-
察話çç°å¢ã§ã¯ããŸãæ©èœããŸãããPythonãã¡ã€ã«çµç±ã§å®è¡ãããš
SyntaxError
ãçºçããŸãïŒãã¡ããåç §ïŒãããããeval
ãcompile
å ã§ã¹ããŒãã¡ã³ããã©ããããããšã§æ©èœãããããšãã§ããŸããfrom __future__ import barry_as_FLUFL print(eval('"Ruby" <> "Python"'))
ⶠPythonã§ãç¥ã£ãŠããããšïŒæã¯è€é
import this
ããããïŒthisïŒã¯äœã ïŒthis
is love â€ïž
åºå:
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Zen of Pythonã§ãïŒ
>>> love = this
>>> this is love
True
>>> love is True
False
>>> love is False
False
>>> love is not True or False
True
>>> love is not True or False; love is love # æã¯è€éã
True
ð¡è§£èª¬:
- Pythonã®
this
ã¢ãžã¥ãŒã«ã¯ãThe Zen of PythonïŒPEP 20ïŒã®ã€ãŒã¹ã¿ãŒãšãã°ã§ãã - èå³ã®ããæ¹ã¯ãthis.pyã®å®è£ ãã確èªãã ãããé¢çœãããšã«ãçŠ ã®ã³ãŒãã¯èªèº«ã«éåããŠããŸãïŒããããå¯äžã®ã±ãŒã¹ã§ãïŒã
love is not True or False; love is love
ãšããæã«é¢ããŠã¯ãç®èãªããšã«èªæã§ãïŒããåãããªããªããis
ãšis not
æŒç®åã«é¢ããäŸãã芧ãã ããïŒã
ⶠå®ã¯ååšãããã§ãïŒïŒ
ã«ãŒãã®ããã® else
ç¯ã 以äžã¯å
žåçãªäŸã§ãïŒ
def does_exists_num(l, to_find):
for num in l:
if num == to_find:
print("ååšããŸãïŒ")
break
else:
print("ååšããŸãã")
åºå:
>>> some_list = [1, 2, 3, 4, 5]
>>> does_exists_num(some_list, 4)
Exists!
>>> does_exists_num(some_list, -1)
Does not exist
äŸå€åŠçã«ããã else
ç¯ã äŸãã°ã
try:
pass
except:
print("Exception occurred!!!")
else:
print("Try block executed successfully...")
åºå:
Try block executed successfully...
ð¡ 解説:
- ã«ãŒãã®åŸã®
else
ç¯ã¯ããã¹ãŠã®ç¹°ãè¿ãã®åŸã«æ瀺çãªbreak
ããªãå Žåã«ã®ã¿å®è¡ãããŸãã"nobreak" ç¯ãšèããããšãã§ããŸãã try
ãããã¯ã®åŸã®else
ç¯ã¯ããå®äºç¯ããšãåŒã°ããŸãããªããªãtry
æã®else
ç¯ã«å°éãããšããããšã¯ãtryãããã¯ãå®éã«æ£åžžã«å®äºããããšãæå³ããããã§ãã
ⶠEllipsis
def some_func():
Ellipsis
åºå
>>> some_func()
# åºåãªãããšã©ãŒãªã
>>> SomeRandomString
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'SomeRandomString' is not defined
>>> Ellipsis
Ellipsis
ð¡ 解説:
-
Pythonã§ã¯ã
Ellipsis
ã¯ã°ããŒãã«ã«å©çšå¯èœãªçµã¿èŸŒã¿ãªããžã§ã¯ãã§ããã...
ãšåçã§ãã>>> ... Ellipsis
çç¥èšå·ã¯ããã€ãã®ç®çã§äœ¿çšã§ããŸãã
- ãŸã æžãããŠããªãã³ãŒãã®ãã¬ãŒã¹ãã«ããŒãšããŠïŒ
pass
æãšåæ§ïŒ - ã¹ã©ã€ã¹æ§æã§ãæ®ãã®æ¹åã®å®å šãªã¹ã©ã€ã¹ãè¡šãããã«äœ¿çš
>>> import numpy as np
>>> three_dimensional_array = np.arange(8).reshape(2, 2, 2)
array([
[
[0, 1],
[2, 3]
],
[
[4, 5],
[6, 7]
]
])
3次å
é
å three_dimensional_array
ã¯é
åã®é
åã®é
åã§ããå
éšã®é
åã®ãã¹ãŠã®ç¬¬2èŠçŽ ïŒã€ã³ããã¯ã¹ 1
ïŒãåºåãããå Žåã¯ãçç¥èšå·ã䜿çšããŠåã«ãã次å
ããã€ãã¹ã§ããŸãã
>>> three_dimensional_array[:,:,1]
array([[1, 3],
[5, 7]])
>>> three_dimensional_array[..., 1] # çç¥èšå·ã䜿çšã
array([[1, 3],
[5, 7]])
- ããã¯ä»»æã®æ¬¡å
æ°ã§æ©èœããŸããæåãšæåŸã®æ¬¡å
ã§ã¹ã©ã€ã¹ãéžæããäžéã®æ¬¡å
ãç¡èŠããããšãã§ããŸãïŒ
n_dimensional_array[firs_dim_slice, ..., last_dim_slice]
ïŒã- åãã³ãã§åã®äžéšã ãã瀺ãããã«äœ¿çšïŒäŸïŒ
(Callable[..., int]
ãTuple[str, ...]
ïŒã - é¢æ°ã®ããã©ã«ãåŒæ°ãšããŠçç¥èšå·ã䜿çšããããšãã§ããŸãïŒ"åŒæ°ãæž¡ãããªã"ãš"Noneå€ãæž¡ããã"ã®ã·ããªãªãåºå¥ãããå ŽåïŒã
- åãã³ãã§åã®äžéšã ãã瀺ãããã«äœ¿çšïŒäŸïŒ
ⶠã€ã³ãããã£
ïŒæã¡ééãã§ã¯ãããŸãããïŒ
åºå (Python 3.x):
>>> infinity = float('infinity')
>>> hash(infinity)
314159
>>> hash(float('-inf'))
-314159
ð¡ 解説:
- ç¡éã®ããã·ã¥ã¯10âµ x Ïã§ãã
- é¢çœãããšã«ãPython 3ã§ã¯
float('-inf')
ã®ããã·ã¥ã¯ "-10âµ x Ï" ã§ãããPython 2ã§ã¯ "-10âµ x e" ã§ãã
ⶠãã³ã°ãªã³ã°ããã
class Yo(object):
def __init__(self):
self.__honey = True
self.bro = True
åºå:
>>> Yo().bro
True
>>> Yo().__honey
AttributeError: 'Yo' object has no attribute '__honey'
>>> Yo()._Yo__honey
True
class Yo(object):
def __init__(self):
# ä»åºŠã¯å¯Ÿç§°çãªãã®ãè©ŠããŠã¿ãŸããã
self.__honey__ = True
self.bro = True
åºå:
>>> Yo().bro
True
>>> Yo()._Yo__honey__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Yo' object has no attribute '_Yo__honey__'
ãªã Yo()._Yo__honey
ã¯æ©èœããã®ã§ããããïŒ
_A__variable = "Some value"
class A(object):
def some_func(self):
return __variable # ãŸã ã©ãã«ãåæåãããŠããªãŸãã
åºå:
>>> A().__variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute '__variable'
>>> A().some_func()
'Some value'
ð¡ 解説:
- ååã®ãã³ã°ãªã³ã°ã¯ãç°ãªãåå空ééã®åœåè¡çªãé¿ããããã«äœ¿çšãããŸãã
- Pythonã§ã¯ã
__
ïŒããã«ã¢ã³ããŒã¹ã³ã¢ã"dunder"ãšãåŒã°ããïŒã§å§ãŸããäžã€ä»¥äžã®æ«å°Ÿã¢ã³ããŒã¹ã³ã¢ã§çµãããªãã¯ã©ã¹ã¡ã³ããŒåã¯ãã¯ã©ã¹åã®åã«_NameOfTheClass
ãè¿œå ããããšã§ä¿®æ£ïŒãã³ã°ãªã³ã°ïŒãããŸãã - ãããã£ãŠãæåã®ã¹ããããã§
__honey
å±æ§ã«ã¢ã¯ã»ã¹ããã«ã¯ãåã«_Yo
ãè¿œå ããå¿ èŠããããŸãããããã«ãããä»ã®ã¯ã©ã¹ã§å®çŸ©ãããåãååã®å±æ§ãšã®è¡çªãé²ãããšãã§ããŸãã - ã§ã¯ããªã2çªç®ã®ã¹ããããã§ã¯æ©èœããªãã£ãã®ã§ããããïŒããã¯ååã®ãã³ã°ãªã³ã°ãäºéã¢ã³ããŒã¹ã³ã¢ã§çµããååãé€å€ããããã§ãã
- 3çªç®ã®ã¹ãããããååã®ãã³ã°ãªã³ã°ã®çµæã§ãã
return __variable
ã®ã¹ããŒãã¡ã³ãå ã®åå__variable
ã¯_A__variable
ã«ãã³ã°ãªã³ã°ãããããã¯å€éšã¹ã³ãŒãã§å®£èšããå€æ°ã®ååãšåãã§ãã - ãŸãããã³ã°ãªã³ã°ãããååã255æåãè¶ ããå Žåã¯ãåãæšãŠãè¡ãããŸãã
ã»ã¯ã·ã§ã³:èŠãç®ã«æãããããª
ⶠè¡ãã¹ãããïŒ
åºå:
>>> value = 11
>>> valuе = 32
>>> value
11
ãã£ïŒ
泚æ: ãããåçŸããæãç°¡åãªæ¹æ³ã¯ãäžèšã®ã¹ããããããã¹ããŒãã¡ã³ããã³ããŒããŠãã¡ã€ã«/ã·ã§ã«ã«è²Œãä»ããããšã§ãã
ð¡ 解説:
äžéšã®é西æŽæåã¯è±åã¢ã«ãã¡ãããã®æåãšåäžã«èŠããŸãããã€ã³ã¿ãŒããªã¿ãŒã«ãã£ãŠç°ãªããã®ãšèŠãªãããŸãã
>>> ord('е') # ããªã«æåã® 'e' (Ye)
1077
>>> ord('e') # ã©ãã³æåã® 'e'ãè±èªã§äœ¿çšãããæšæºããŒããŒãã§å
¥å
101
>>> 'е' == 'e'
False
>>> value = 42 # ã©ãã³æåã® e>>> valuе = 23 # ããªã«æåã® 'e', Python 2.x ã€ã³ã¿ãŒããªã¿ãŒã¯ãã㧠`SyntaxError` ãçºçããã>>> value
42
çµã¿èŸŒã¿ã® ord()
é¢æ°ã¯æåã®Unicode ã³ãŒããã€ã³ããè¿ããããªã«æåã® 'e' ãšã©ãã³æåã® 'e' ã®ç°ãªãã³ãŒãäœçœ®ãäžèšã®äŸã®æ¯ãèããæ£åœåããŸãã
ⶠãã¬ããŒããŒã·ã§ã³
# `pip install numpy` ãå
ã«å®è¡
import numpy as np
def energy_send(x):
# numpyé
åãåæå
np.array([float(x)])
def energy_receive():
# 空ã®numpyé
åãè¿ã
return np.empty((), dtype=np.float).tolist()
åºå:
>>> energy_send(123.456)
>>> energy_receive()
123.456
ããŒãã«è³ã¯ã©ããžïŒ
ð¡ 解説:
energy_send
é¢æ°ã§äœæãããnumpyé åãè¿ãããªãããšã«ã泚æãã ããããã®ããããã®ã¡ã¢ãªã¹ããŒã¹ã¯åå²ãåœãŠå¯èœã§ããnumpy.empty()
ã¯åæåããã«æ¬¡ã®ç©ºãã¡ã¢ãªã¹ããããè¿ããŸãããã®ã¡ã¢ãªäœçœ®ã¯ããŸããŸã¡ããã©è§£æŸããããã®ãšåãã§ãïŒéåžžã¯ããã§ãããå¿ ãããããã§ã¯ãããŸããïŒã
ⶠäœããããããâŠ
def square(x):
"""
A simple function to calculate the square of a number by addition.
"""
sum_so_far = 0
for counter in range(x):
sum_so_far = sum_so_far + x
return sum_so_far
åºå (Python 2.x):
>>> square(10)
10
ãªã100ã§ã¯ãªãã®ã§ããããïŒ
泚: åçŸã§ããªãå Žåã¯ãã·ã§ã«çµç±ã§ãã¡ã€ã« mixed_tabs_and_spaces.py ãå®è¡ããŠã¿ãŠãã ããã
ð¡ 解説:
-
ã¿ããšã¹ããŒã¹ãæ··åšãããªãã§ãã ããïŒ
return
ã®çŽåã®æå㯠"ã¿ã" ã§ãäŸã®ä»ã®å Žæã§ã¯ "4ã¹ããŒã¹" ã®åæ°ã§ã€ã³ãã³ããããŠããŸãã -
Pythonãã¿ããã©ã®ããã«æ±ããã¯ä»¥äžã®éãã§ãã
ãŸããã¿ãã¯å·Šããå³ãžãš1ãã8ã®ã¹ããŒã¹ã«çœ®ãæãããã眮ãæããå«ããç·æåæ°ã8ã®åæ°ãšãªãããã«ãããŸã<...>
-
ãããã£ãŠã
square
é¢æ°ã®æåŸã®è¡ã® "ã¿ã" ã¯8ã€ã®ã¹ããŒã¹ã«çœ®ãæããããã«ãŒãã«å ¥ã蟌ã¿ãŸãã -
Python 3ã¯ããã®ãããªå Žåã«èªåçã«ãšã©ãŒãæããŠãããã®ã§èŠªåã§ãã
åºå (Python 3.x):
TabError: inconsistent use of tabs and spaces in indentation
ã»ã¯ã·ã§ã³:ããŸããŸãªãããã¯
+=
ã®æ¹ãéã
ⶠ# "+", äžã€ã®æååã䜿ã£ãŠ:
>>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100)
0.25748300552368164
# "+=", äžã€ã®æååã䜿ã£ãŠ:
>>> timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100)
0.012188911437988281
ð¡ 解説:
- äºã€ä»¥äžã®æååãé£çµããå Žåã
+=
ã¯+
ãããéãã§ãããªããªãæåã®æååïŒs1 += s2 + s3
ã®å Žåã®s1
ãªã©ïŒãå®å šãªæååãèšç®ããéã«ç Žå£ãããªãããã§ãã
ⶠ巚倧ãªæååã®äœæ
def add_string_with_plus(iters):
s = ""
for i in range(iters):
s += "xyz"
assert len(s) == 3*iters
def add_bytes_with_plus(iters):
s = b""
for i in range(iters):
s += b"xyz"
assert len(s) == 3*iters
def add_string_with_format(iters):
fs = "{}"*iters
s = fs.format(*(["xyz"]*iters))
assert len(s) == 3*iters
def add_string_with_join(iters):
l = []
for i in range(iters):
l.append("xyz")
s = "".join(l)
assert len(s) == 3*iters
def convert_list_to_string(l, iters):
s = "".join(l)
assert len(s) == 3*iters
åºå:
# çµæã®èªã¿ãããã®ããã« ipython ã·ã§ã«ã§ %timeit ã䜿çšããŠå®è¡ãããŸããã
# æšæºã® python ã·ã§ã«/ã¹ã¯ãªããã§ã¯ timeit ã¢ãžã¥ãŒã«ã䜿çšããããšãã§ããŸãã䜿çšäŸã¯ä»¥äžã®éãã§ãã
# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())
>>> NUM_ITERS = 1000
>>> %timeit -n1000 add_string_with_plus(NUM_ITERS)
124 µs ± 4.73 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS)
211 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit -n1000 add_string_with_format(NUM_ITERS)
61 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit -n1000 add_string_with_join(NUM_ITERS)
117 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> l = ["xyz"]*NUM_ITERS
>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS)
10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
ã€ãã¬ãŒã·ã§ã³åæ°ã10åã«å¢ãããŠã¿ãŸãããã
>>> NUM_ITERS = 10000>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) # å®è¡æéãç·åœ¢ã«å¢å
1.26 ms ± 76.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) # äºæ¬¡çã«å¢å
6.82 ms ± 134 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit -n1000 add_string_with_format(NUM_ITERS) # ç·åœ¢ã«å¢å
645 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit -n1000 add_string_with_join(NUM_ITERS) # ç·åœ¢ã«å¢å
1.17 ms ± 7.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> l = ["xyz"]*NUM_ITERS
>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) # ç·åœ¢ã«å¢å
86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
ð¡ 解説:
-
timeitã%timeitã«ã€ããŠã¯ããªã³ã¯å ã§è©³ãã解説ãèªãããšãã§ããŸãããããã¯ã³ãŒãã®å®è¡æéã枬å®ããããã«äœ¿çšãããŸãã
-
é·ãæååã®çæã«ã¯
+
ã䜿çšããªãã§ãã ãã â Pythonã§ã¯ãstr
ã¯äžå€ãªã®ã§ã2ã€ã®æååãé£çµãããã³ã«ãå·Šå³ã®æååãæ°ããæååã«ã³ããŒãããªããã°ãªããŸããã10æåã®4ã€ã®æååãé£çµããå Žåã40æåã§ã¯ãªã90æåïŒ(10+10) + ((10+10)+10) + (((10+10)+10)+10)ïŒãã³ããŒããããšã«ãªããŸããæååã®æ°ãšãµã€ãºãå¢ããã«ã€ããŠãç¶æ³ã¯äºæ¬¡çã«æªåããŸãïŒadd_bytes_with_plus
é¢æ°ã®å®è¡æéã§æ£åœåãããŠããŸãïŒã -
ãã®ããã
.format.
ãŸãã¯%
æ§æã®äœ¿çšãæšå¥šãããŸãïŒãã ããéåžžã«çãæååã®å Žåã¯+
ããããããã«é ãã§ãïŒã -
ããã«è¯ãæ¹æ³ã¯ãæ¢ã«å 容ãiterableãªããžã§ã¯ãã®åœ¢ã§å©çšå¯èœã§ããã°ã
''.join(iterable_object)
ã䜿çšããããšã§ããããã¯å§åçã«éãã§ãã -
åã®äŸã§è°è«ããã
+=
ã®æé©åã®ãããadd_bytes_with_plus
ãšã¯ç°ãªããadd_string_with_plus
ã¯å®è¡æéã®äºæ¬¡çãªå¢å ã瀺ããŸããã§ãããs += "xyz"
ã®ä»£ããã«s = s + "x" + "y" + "z"
ã§ãã£ãå Žåãå¢å ã¯äºæ¬¡çã«ãªããŸããdef add_string_with_plus(iters): s = "" for i in range(iters): s = s + "x" + "y" + "z" assert len(s) == 3*iters >>> %timeit -n100 add_string_with_plus(1000) 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) >>> %timeit -n100 add_string_with_plus(10000) # å®è¡æéã®äºæ¬¡çãªå¢å 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
-
巚倧ãªæååã圢æãããã©ãŒãããã®æ¹æ³ãå€ãããã®ã¯ãZen of Pythonãšå¯Ÿç«ããŠããããã§ããããŸãã以äžåŒçšã
ãããè¡ãæ¹æ³ã¯äžã€ã ãã§ãããã§ããã°ãã äžã€ã®æçœãªæ¹æ³ãããã¹ãã§ãã
dict
æ€çŽ¢ã®é
延
ⶠsome_dict = {str(i): 1 for i in range(1_000_000)}
another_dict = {str(i): 1 for i in range(1_000_000)}
åºå:
>>> %timeit some_dict['5']
28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> some_dict[1] = 1
>>> %timeit some_dict['5']
37.2 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> %timeit another_dict['5']
28.5 ns ± 0.142 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> another_dict[1] # Trying to access a key that doesn't exist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 1
>>> %timeit another_dict['5']
38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
ãªãåãæ€çŽ¢ãé ããªãã®ã§ããããïŒ
ð¡ 解説:
- CPythonã«ã¯ããã¹ãŠã®ããŒã¿ã€ãïŒ
str
ãint
ãä»»æã®ãªããžã§ã¯ã...ïŒãæ±ãæ±çšã®èŸæžæ€çŽ¢é¢æ°ãšãstr
ã®ã¿ããæ§æãããèŸæžã®äžè¬çãªã±ãŒã¹çšã®ç¹åããé¢æ°ããããŸãã - ç¹åããé¢æ°ïŒCPythonã®ãœãŒã¹ã§ã¯
lookdict_unicode
ãšåœåãããŠããŸãïŒã¯ããã¹ãŠã®ããŒïŒæ€çŽ¢ãããããŒãå«ãïŒãæååã§ããããšãç¥ã£ãŠããã__eq__
ã¡ãœãããåŒã³åºã代ããã«ãããé«éãã€åçŽãªæååæ¯èŒã䜿çšããŠããŒãæ¯èŒããŸãã dict
ã€ã³ã¹ã¿ã³ã¹ãéstr
ããŒã§ã¢ã¯ã»ã¹ããããšãå°æ¥ã®æ€çŽ¢ã§æ±çšé¢æ°ã䜿çšããããã«å€æŽãããŸãã- ãã®ããã»ã¹ã¯ç¹å®ã®
dict
ã€ã³ã¹ã¿ã³ã¹ã«å¯ŸããŠã¯å ã«æ»ãããšãã§ãããããŒãèŸæžã«ååšããå¿ èŠããããŸããããã®ããã倱æããã«ãã¯ã¢ãããè©Šã¿ãããšã§ãåãå¹æããããŸãã
dict
ã®èšåŒµ
ⶠã€ã³ã¹ã¿ã³ã¹import sys
class SomeClass:
def __init__(self):
self.some_attr1 = 1
self.some_attr2 = 2
self.some_attr3 = 3
self.some_attr4 = 4
def dict_size(o):
return sys.getsizeof(o.__dict__)
åºå: (Python 3.8ãä»ã®Python 3ããŒãžã§ã³ã¯å°ãç°ãªãå ŽåããããŸã)
>>> o1 = SomeClass()
>>> o2 = SomeClass()
>>> dict_size(o1)
104
>>> dict_size(o2)
104
>>> del o1.some_attr1
>>> o3 = SomeClass()
>>> dict_size(o3)
232
>>> dict_size(o1)
2
ããäžåºŠè©ŠããŠã¿ãŸããã... æ°ããã€ã³ã¿ãŒããªã¿ãŒã§:
>>> o1 = SomeClass()
>>> o2 = SomeClass()
>>> dict_size(o1)
104 # äºæ³éã
>>> o1.some_attr5 = 5>>> o1.some_attr6 = 6>>> dict_size(o1)
360
>>> dict_size(o2)
272
>>> o3 = SomeClass()
>>> dict_size(o3)
232
ãããã®èŸæžãèšåŒµããåå ã¯äœã§ããããïŒãŸããæ°ããäœæããããªããžã§ã¯ããèšåŒµããŠããã®ã¯ãªãã§ããããïŒ
ð¡ 解説:
- CPythonã¯è€æ°ã®èŸæžã§åã"ããŒ"ãªããžã§ã¯ããåå©çšããããšãã§ããŸããããã¯PEP 412ã§è¿œå ãããç¹ã«ã€ã³ã¹ã¿ã³ã¹ã®èŸæžã§ã¡ã¢ãªäœ¿çšéãåæžããããšãç®çãšããŠããŸã - ããŒïŒã€ã³ã¹ã¿ã³ã¹å±æ§ïŒã¯ãã¹ãŠã®ã€ã³ã¹ã¿ã³ã¹ã«å ±éããåŸåããããŸãã
- ãã®æé©åã¯ã€ã³ã¹ã¿ã³ã¹èŸæžã«å®å šã«ééçã§ãããç¹å®ã®åæãç Žããããšç¡å¹ã«ãªããŸãã
- ããŒå ±æèŸæžã¯åé€ããµããŒãããŠããŸãããã€ã³ã¹ã¿ã³ã¹å±æ§ãåé€ããããšãèŸæžã¯ãå ±æ解é€ããããåãã¯ã©ã¹ã®å°æ¥ã®ãã¹ãŠã®ã€ã³ã¹ã¿ã³ã¹ã«å¯ŸããŠããŒå ±æãç¡å¹ã«ãªããŸãã
- ããã«ãèŸæžã®ããŒããªãµã€ãºãããå ŽåïŒæ°ããããŒãæ¿å
¥ãããããïŒãããã㯠ãã äžã€ã®èŸæž ã«ãã£ãŠäœ¿çšãããŠããå Žåã«ã®ã¿å
±æãããŸãïŒããã«ãããæåã«äœæãããã€ã³ã¹ã¿ã³ã¹ã®
__init__
å ã§å€ãã®å±æ§ãè¿œå ããŠããå ±æ解é€ããçºçãããå ±æãç¶ç¶ãããŸãïŒãè€æ°ã®ã€ã³ã¹ã¿ã³ã¹ãååšããç¶æ ã§ãªãµã€ãºãçºçãããšãåãã¯ã©ã¹ã®å°æ¥ã®ãã¹ãŠã®ã€ã³ã¹ã¿ã³ã¹ã«å¯ŸããŠããŒå ±æãç¡å¹ã«ãªããŸãïŒCPythonã¯ã€ã³ã¹ã¿ã³ã¹ãåãå±æ§ã»ããã䜿çšããŠãããã©ãããå€æã§ããªããªããããŒã®å ±æãè©Šã¿ãããšãè«ŠããŸãã - ããã°ã©ã ã®ã¡ã¢ãªãããããªã³ããäœæžããããå Žåã®å°ããªãã³ãïŒã€ã³ã¹ã¿ã³ã¹å±æ§ãåé€ããªãã§ãã ããããããŠ
__init__
å ã§ãã¹ãŠã®å±æ§ãåæåããŠãã ããïŒ
ⶠãã®ä»ã®å°ããªçºèŠ
-
join()
ã¯ãªã¹ãæäœã§ã¯ãªãæååæäœã§ããïŒæåã«äœ¿ããšãã¯çŽæã«åãããããããŸããïŒð¡ 説æ:
join()
ãæååã®ã¡ãœãããªããä»»æã®ã€ãã©ãã«ïŒãªã¹ããã¿ãã«ãã€ãã¬ãŒã¿ïŒã«å¯ŸããŠæäœãè¡ãããšãã§ããŸãããªã¹ãã®ã¡ãœããã§ããã°ãåã¿ã€ãããšã«å¥ã ã«å®è£ ããå¿ èŠããããŸãããŸããäžè¬çãªlist
ãªããžã§ã¯ãã®APIã«æååå°çšã®ã¡ãœãããèšããããšã¯ããŸãæå³ããããŸããã -
å¥åŠã«èŠãããæå³çã«ã¯æ£ããã¹ããŒãã¡ã³ãïŒ
[] = ()
ã¯æå³çã«æ£ããã¹ããŒãã¡ã³ãã§ãïŒç©ºã®tuple
ã空ã®list
ã«å±éããŠããŸãïŒ'a'[0][0][0][0][0]
ãæå³çã«ã¯æ£ããã§ããPythonã«ã¯ä»ã®Cãã掟çããèšèªã®ãããªãã£ã©ã¯ã¿ãŒããŒã¿åããªããããæååãã1æåãéžæãããš1æåã®æååãè¿ãããŸãã3 --0-- 5 == 8
ãš5 == 5
ã¯äž¡æ¹ãšãæå³çã«æ£ããã¹ããŒãã¡ã³ãã§ãçµæã¯True
ã«ãªããŸãã
-
a
ãæ°å€ã§ããå Žåã++a
ãša
ã¯æå¹ãªPythonã¹ããŒãã¡ã³ãã§ãããCãC++ãJavaãªã©ã®èšèªã§ã®é¡äŒŒã®ã¹ããŒãã¡ã³ããšã¯åããããªåäœã¯ããŸããã>>> a = 5 >>> a 5 >>> ++a 5 >>> --a 5
-
ð¡ 解説:
- Pythonã®ææ³ã«ã¯
++
æŒç®åãååšããŸãããå®éã«ã¯2ã€ã®+
æŒç®åããããŸãã ++a
ã¯+(+a)
ãšããŠè§£æãããçµæãšããŠa
ã«ãªããŸããåæ§ã«ãa
ã®ã¹ããŒãã¡ã³ãã®åºåãæ£åœåã§ããŸãã- Pythonã«ã€ã³ã¯ãªã¡ã³ããšãã¯ãªã¡ã³ãæŒç®åããªãçç±ã«ã€ããŠã¯ãã®StackOverflow ã¹ã¬ããã§è°è«ãããŠããŸãã
- Pythonã®ææ³ã«ã¯
-
ã»ã€ãŠãæŒç®åã«ã€ããŠã¯ç¥ã£ãŠããŸãããããããã¹ããŒã¹ã€ã³ããŒããŒæŒç®åã«ã€ããŠã¯èããããšããããŸããïŒ
>>> a = 42 >>> a -=- 1 >>> a 43
ããã¯ãå¥ã®ã€ã³ã¯ãªã¡ã³ãæŒç®åãšäžç·ã«äœ¿ããã代æ¿ã®ã€ã³ã¯ãªã¡ã³ãæŒç®åã§ãã
>>> a +=+ 1
>>> a
>>> 44
- ð¡ 解説:
ãã®ãžã§ãŒã¯ã¯ Raymond Hettingerã®ãã€ãŒãããããŠããŸããã¹ããŒã¹ã€ã³ããŒããŒæŒç®åã¯å®éã«ã¯ééã£ã圢åŒã® a -= (-1)
ã§ãããã㯠a = a - (- 1)
ãšç䟡ã§ããa += (+ 1)
ã®ã±ãŒã¹ãåæ§ã§ãã
-
Pythonã«ã¯ææžåãããŠããªãéå«ææŒç®åããããŸãã
>>> False ** False == True True >>> False ** True == False True >>> True ** False == True True >>> True ** True == True True
-
ð¡ 解説:
False
ãšTrue
ã0ãš1ã«çœ®ãæããŠèšç®ãããšãççå€è¡šã¯éå«ææŒç®åãšç䟡ã«ãªããŸãã(åºå ž) -
æŒç®åã®è©±é¡ã§ããããè¡åä¹ç®ã®ããã®
@
æŒç®åããããŸãïŒå¿é ããªãã§ãã ãããä»åã¯æ¬ç©ã§ãïŒã>>> import numpy as np >>> np.array([2, 2, 2]) @ np.array([7, 8, 8]) 46
-
ð¡ 解説:
@
æŒç®åã¯ãç§åŠã³ãã¥ããã£ã念é ã«çœ®ããŠPython 3.5ã§è¿œå ãããŸãããä»»æã®ãªããžã§ã¯ãã¯__matmul__
ããžãã¯ã¡ãœããããªãŒããŒããŒãããŠãã®æŒç®åã®åäœãå®çŸ©ããããšãã§ããŸãã -
Python 3.8以éã§ã¯ã
f'{some_var=}
ã®ãããªå žåçãªfæååæ§æã䜿ã£ãŠçŽ æ©ããããã°ã§ããŸããäŸãã°ã>>> some_string = "wtfpython">>> f'{some_string=}' "some_string='wtfpython'"
Pythonã§ã¯é¢æ°å ã®ããŒã«ã«å€æ°ã®æ ŒçŽã«2ãã€ãã䜿çšããŸããçè«çã«ã¯ãé¢æ°å ã«65536åã®å€æ°ããå®çŸ©ã§ããªãããšãæå³ããŸããããããPythonã«ã¯2^16å以äžã®å€æ°åãæ ŒçŽããããã®äŸ¿å©ãªå èµãœãªã¥ãŒã·ã§ã³ããããŸãã以äžã®ã³ãŒãã¯ã65536å以äžã®ããŒã«ã«å€æ°ãå®çŸ©ããããšãã«ã¹ã¿ãã¯ã§äœãèµ·ãããã瀺ããŠããŸãïŒèŠåïŒãã®ã³ãŒãã¯çŽ2^18è¡ã®ããã¹ããåºåããã®ã§ãèŠæããŠãã ããïŒïŒïŒ
import dis
exec("""
def f():
""" + """
""".join(["X" + str(x) + "=" + str(x) for x in range(65539)]))
f()
print(dis.dis(f))
-
è€æ°ã®Pythonã¹ã¬ããã¯Pythonã³ãŒããåæã«å®è¡ããŸããïŒèŽãééãã§ã¯ãããŸãããïŒïŒãè€æ°ã®ã¹ã¬ãããçæããŠPythonã³ãŒããåæã«å®è¡ããã®ã¯çŽæçã«æãããããããŸããããPythonã®Global Interpreter Lockã®ãããå®éã«ã¯ã¹ã¬ãããåãã³ã¢ã§äº€äºã«å®è¡ãããŠããã ãã§ããPythonã®ã¹ã¬ããã¯IOããŠã³ãã¿ã¹ã¯ã«é©ããŠããŸãããCPUããŠã³ãã¿ã¹ã¯ã§å®éã®äžŠååãéæããã«ã¯ãPythonã®multiprocessingã¢ãžã¥ãŒã«ã䜿çšããããšãæ€èšãããããããŸããã
-
print
ã¡ãœããã¯å€ãããã«åºåããªãããšããããŸããäŸãã°ã# ãã¡ã€ã« some_file.py import time print("wtfpython", end="_") time.sleep(3)
-
ããã¯ã
end
åŒæ°ã®ããã«ãåºåãããã¡ã\n
ã«ééããããããã°ã©ã ã®å®è¡ãçµäºãããŸã§ãã©ãã·ã¥ãããªããããwtfpython
ã3ç§åŸã«åºåãããŸãããããã¡ããã©ãã·ã¥ããããã«ã¯flush=True
åŒæ°ãæž¡ãããšãã§ããŸãã -
ç¯å²å€ã®ã€ã³ããã¯ã¹ã䜿ã£ããªã¹ãã®ã¹ã©ã€ã¹ã¯ãšã©ãŒãæããŸããã
>>> some_list = [1, 2, 3, 4, 5] >>> some_list[111:] []
-
iterableãã¹ã©ã€ã¹ãããšåžžã«æ°ãããªããžã§ã¯ããäœãããããã§ã¯ãããŸãããäŸãã°ã
>>> some_str = "wtfpython" >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n'] >>> some_list is some_list[:] # æ°ãããªããžã§ã¯ããäœãããã®ã§Falseãäºæ³ããã False >>> some_str is some_str[:] # æååã¯äžå€ãªã®ã§ãæ°ãããªããžã§ã¯ããäœãããšã¯ããŸãæå³ããªããããTrueã True
-
Python 3ã§ã¯ã
int('١٢٣ـ٥ي٧ٚ٩')
ã¯123456789
ãè¿ããŸããPythonã«ãããDecimal charactersïŒåé²æ°æåïŒã«ã¯ãæ°åæåãšãåé²æ°ã圢æããããã«äœ¿ããå šãŠã®æåãå«ãŸããŸããäŸãã°ãU+0660, ARABIC-INDIC DIGIT ZEROã§ããããã«é¢é£ããé¢çœã話ããããŸãã -
Python 3以éãæ°åãªãã©ã«ã¯ã¢ã³ããŒã¹ã³ã¢ïŒ
_
ïŒã䜿ã£ãŠåºåãããšãã§ããŸãïŒèªã¿ããããåäžãããããïŒã
>>> six_million = 6_000_000
>>> six_million
6000000
>>> hex_address = 0xF00D_CAFE
>>> hex_address
4027435774
-
'abc'.count('') == 4
ãããã«count
ã¡ãœããã®ããããã®å®è£ ãããããããäºæ ãããæ確ã«ããŸããdef count(s, sub): result = 0 for i in range(len(s) + 1 - len(sub)): result += (s[i:i + len(sub)] == sub) return result
ã»ãã®æåã¯ããªãªãžãã«ã®æååã«ãããŠé·ã0ã®ã¹ã©ã€ã¹ãšç©ºã®éšåæååïŒ''
ïŒãäžèŽããããã§ãã