日々、StackOverflow や Qiita や Medium らで pythonについてググっている私がこれ使えるな、面白いなと思った tips や tricks, ハックを載せていくよ。
詳しく知りたい場合はpython documentationへ GO!!
簡単な例文だけ載せてくスタイル。新しいの発見次第、じゃんじゃん頻繁に追加していくよ。
これも知っとけ!これ間違ってる!ってのがあったら、コメント please!!
このmoduleやlibraryのfunctionとか基本的な使い方を知りたいけど、自分で探すの面倒、英語意味不ってのがありましたらそれもコメントにどうぞ。私が代わりに調査,解析を努力致します。
*first class function, closure, decorator やspecific libraries, modulesについてここで書くよりかも別の記事として、書こうかなと思うけど需要があれば書きます。
目指せ、パイソニスタ!
Basic :基本
print()
# print()は、末尾に改行を追加して出力するのがデフォルト
# end=
print("hello" end='\t')
print("world")
# ---> hello world
# 改行せずに1タブ分空くよ
# end=
print("python" end="")
print("awesome")
# ---> pythonawesome
# space がないよ
# sep=
print('Cats', 'Dogs', 'Pigs', sep=' & ')
# ---> Cats & Dogs & Pigs
How to check if list is empty
a = []
if a:
print("ok")
else:
print("bye")
# ---> bye
if not a:
print("empty")
# ---> empty
# NOT RECOMMENDED!
if len(a) == 0: print("a is empty")
# ---> a is empty
# BAD WAY
if a == []:
print('a is an empty list')
# ---> a is an empty list
Converting to binary
# "Converting integer to binary"
print("{0:b}".format(1))
# ---> 1
print('{0:08b}'.format(1))
# ---> 00000001
print(format(1, '08b'))
# ---> 00000001
print(f'{1:08b}')
# ---> 00000001
print(bin(1))
# ---> 0b1
print(bin(1)[2:].zfill(8))
# ---> 00000001
############################
print("{0:b}".format(2))
# ---> 10
print("{0:b}".format(5))
# ---> 101
print("{0:b}".format(80))
# ---> 1010000
Ternary Operator
y = 9
# y が 9 だったら x = 10, それ以外だったら x = 20
x = 10 if (y == 9) else 20
# 上の例と同義
if y == 9:
x = 10
else:
x = 20
#変数ansが if条件と一致していれば 二つのクラスのうち, その中の一つのclass constructorを呼ぶ
class Dog:
def __init__(self, name):
print("dog's name is ", name)
class Cat:
def __init__(self, name):
print("cat's name is ", name)
ans = "yes"
my_pet = (Dog if ans == "yes" else Cat)("Bruce")
# ---> dog's name is Bruce
# ans が if とマッチしているので、my_pet = Dog("Bruce")
# 基本構造: x = (classA if y == True else classB)(param1, param2)
Decorator
- decoratorの基礎を簡単な例で説明するよ
- 詳しくは:https://www.python.org/dev/peps/pep-0318/#syntax-forms
- もっと難しいのくれよって人には:https://www.codementor.io/sheena/advanced-use-python-decorators-class-function-du107nxsv
- decorator の前にfunctionを理解しよう
def hey(name="namibillow"):
return "hey " + name
print(hey())
# ---> hey namibillow
# 関数を変数に代入
# 注意: greeting = hey() だと hey functionを呼んでしまうyo
greeting = hey()
print(greeting)
# ---> hey namibillow
# 関数を呼ばずに関数ごとを渡すよ
greeting = hey
print(greeting)
# ---> <function hey at 0x101bb7e18>
print(greeting())
# ---> hey namibillow
# delete hey
del hey
print(hey())
# ---> NameError
print(greet())
# ---> hey namibillow
頭がこんがらがったら自分はこう考えてます。
- 関数を呼ぶ、()をつける イコール 風呂敷の中身を広げたまんま変数aさんに渡す
- 関数を()なしで変数に代入 イコール 風呂敷を包んだまんま変数aさんに渡す。a さんは自分で風呂敷を開けなきゃいけない( ()をつける)
# pythonではfunctionの中に、いくつものfunctionを定義できるよ
def greetings(name="kame"):
print(name, "is inside the greetings() function!")
def morning():
return "now ", name, " is in the morning() function"
def night():
return "now ", name, " is in the night() function"
print(morning())
print(night())
print(name, "is back in the greetings() function!")
# greetings関数を呼ぶと morning(), night() も呼ばれるよ
greetings()
# ---> kame is inside the greetings() function!
# now kame is in the morning() function
# now kame is in the night() function
# kame is back in the greetings() function!
morning()
# ---> NameError: name 'morning' is not defined
# 中のfunctionはouter function外からじゃ呼べないよ
########################################################
def hi(name="nami"):
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
if name == "nami":
return greet # greet()だと処理した結果を返しちゃうよ
else:
return welcome # 関数を返すよ
# 変数a に関数hi()のreturnされたものを代入 (この場合 greet関数 が返される)
a = hi()
print(a)
# ---> <function hi.<locals>.greet at 0x104188488>
# つまり a は現在 関数hi() 内の 関数greetのメモリーアドレスを指している
# hi() は greet か welcome関数自体を返すよ
print(hi()())
# ---> now you are in the greet() function
print(a())
# ---> now you are in the greet() function
# 関数に他の関数を引数として渡せるよ
def afterEat():
return 'ごちそうさまでした'
def beforeEat(func):
print("いただきます")
print(func())
beforeEat(afterEat)
# ---> いただきます
# ごちそうさまでした
- それじゃあdecorator いってみよー
def a_decorator(a_func):
print("a_decorator内だよ")
def wrap():
print("a_func() がまだ呼ばれる前だよ")
a_func()
# decoratorで渡された 関数a_funcをa_decorator()内の関数wrap()内で呼ぶよ
print("a_func() はもう呼ばれ終わったよ!")
return wrap # 関数を返すよ
def calling():
print("名前はcalling だけど a_decorator関数内でのニックネームは a_func だよ")
calling = a_decorator(calling)
# now calling is wrapped by wrap()
calling()
# ---> a_decorator内だよ
# a_func() がまだ呼ばれる前だよ
# 名前はcalling だけど a_decorator関数内でのニックネームは a_func だよ
# a_func() はもう呼ばれ終わったよ
# @で呼んでもいいよ
@a_decorator
def calling():
print("名前はcalling だけど a_decorator関数内でのニックネームは a_func だよ")
calling()
# ---> a_decorator内だよ
# a_func() がまだ呼ばれる前だよ
# 名前はcalling だけど a_decorator関数内でのニックネームは a_func だよ
# a_func() はもう呼ばれ終わったよ
# @a_decoratorをdef calling()前につけるのは
# calling = a_decorator(calling)を省略したのと一緒だよ
itertools
import itertools
# list in list を、 1 list にしたい時
a = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
list(itertools.chain.from_iterable(a))
# ---> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
more_itertools
import more_itertools
test = [[-1, -2], [1, 2, 3, [4, (5, [6, 7])]], (30, 40), [25, 35]]
print(list(more_itertools.collapse(test)))
# ---> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
Return multiple variables
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
# ---> 1 2 3 4
Enums
class Shapes:
Circle, Square, Triangle, Quadrangle = range(4)
print(Shapes.Circle)
# ---> 0
print(Shapes.Square)
# ---> 1
print(Shapes.Triangle)
# ---> 2
print(Shapes.Quadrangle)
# ---> 3
zfill()
# 注意:変数は文字列じゃなきゃzfill()は使えないよ
str = '2'
print(str.zfill(2))
# ---> 02
str = 'abc'
print(str.zfill(5))
# ---> 00abc
String formatting
# f''は、Python3.6以降のみ使用可能
a = 40
print(f'this is {a}')
# ---> this is 40
print('it is same as {}'.format(a))
# ---> it is same as 40
print('also same as %d' % (a))
# ---> also same as 40
Out of range な時
list = ['a', 'b', 'c', 'd', 'e']
print(list[10:])
# ---> []
# 空っぽ
filter
numbers = [0, 1, 2, 3, 4, 5]
# 偶数のみ返す
def is_even(numbers):
return numbers % 2 == 0
filteredVowels = filter(is_even, numbers)
print(list(filteredVowels))
# ---> [0,2,4]
update()
# パラメータにはdictionary, an iterable object of key/value pairs (generally tuples)を渡すことができるよ
# does not return any value. 何も返されないよ
d = {1: "one", 2: "three"}
d1 = {2: "two"}
# updates the value of key 2
d.update(d1)
print(d)
# ---> {1: 'one', 2: 'two'}
d1 = {3: "three"}
# adds element with key 3
d.update(d1)
print(d)
# ---> {1: 'one', 2: 'two', 3: 'three'}
d = {'x': 2}
d.update(y = 3, z = 0)
print(d)
# ---> {'x': 2, 'y': 3, 'z': 0}
any(), all()
x = [True, True, False]
# any(): どれか一つでもtrueがあるなら
if any(x):
print("At least one True")
# ---> At least one True
# all(): 全てtrueなら
if all(x):
print("Not one False")
else:
print("There is False")
# ---> There is False
# どれか一つでもtrueであり、なおかつ全てtrue出ないなら
if any(x) and not all(x):
print("At least one True and one False")
# ---> At least one True and one False
print(any([]))
# ---> False
print(any([1]))
# ---> True
zip()
print("ZIP function:")
a = [1, 2, 3]
b = [4, 5, 6]
c = zip(a, b)
for d in c:
print(d)
# ---> (1, 4)
# (2, 5)
# (3, 6)
変数
x, y = 10, 20
print(x, y)
# ---> 10,20
x, y = y, x
print(x, y)
# ---> 20,10
a = ["This", "is", "awesome."]
print(" ".join(a))
# ---> This is awesome.
n = 10
result = 1 < n < 20
print(result)
# ---> True
Dictionary Comprehension
- リストのみならず、ディクショナリーやセットでもできるよ
testDict = {i: i * i for i in range(5)}
print(testDict)
# ---> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Unpacking
a, b, c = (2 * i for i in range(3))
print(a, b, c)
# ---> 0 2 4
def unpack(x, y, z):
print(x, y, z)
testDict = {'x': 1, 'y': 2, 'z': 3}
print(unpack(*testDict))
# ---> x y z
print(unpack(**testDict))
# ---> 1 2 3
dir()
# モジュール内で定義されている関数、属性などの一覧を取得
# 引数なしの場合は自分自身の属性
print(dir())
# ---> ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__',
# '__loader__', '__name__', '__package__', '__spec__', 'a', 'str', 'x']
# 引数にモジュールを渡した時にはそのモジュール内で定義されている属性
import string
print dir(string)
# ---> ['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
print(dir('hey')
# ---> ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
inspect
import inspect
print("this code appears on line: ", inspect.currentframe().f_lineno)
# ---> 17
# コード内での何行目かを出力
map()
print("map function:")
x = [1, 2, 3]
y = map(lambda x: x + 1, x) # x[0], x[1], x[2]とindex ごとにループしてそれぞれに1を足す
print(list(y))
# ---> [2,3,4]
def square(x):
return x*x
squares = map(square, [1, 2, 3])
print(list(squares))
# ---> [1, 4, 9]
print(list(squares))
# ---> []
# アレッ!最後のリストが空っぽじゃあないか!なんで?
# python3 から map() は iteratorを返すようになったので一回ポッキリしか使えないのだ
# リストで返したい場合:
solution1 = list(map(square, [1, 2, 3]))
# 又は
solution2 = [*map(square, [1, 2, 3])]
List comprehension
- 個人的にはmap, filter, reduce()よりかも内包表記の方が読みやすく理解しやすい
- Map と list comprehension と 普通のfor loop文のどれが速いのか知りたい方は下のリンクをどうぞ
- https://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops
- https://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map
- 読む限り、ケースにもよるけど大抵は内包表記の方がまあ速い,と唄う人が多くみられるぞ
# 偶数のみのリストが欲しい場合
L = [i for i in range(10) if i % 2 == 0]
print(L)
# ---> [0, 2, 4, 6, 8]
################################
# nested lists を一つのリストに
matrix = [[1,2,3], [4,5,6]]
# 間違え
L = [x for x in row for row in matrix]
# 正解
L = [x for row in matrix for x in row]
print(L)
# ---> [1, 2, 3, 4, 5, 6]
# nested for loop??どっから読めばいいの??
# そんな時は実際にfor loopで書いてみよう
L = []
for row in matrix:
for x in row:
L.append(x)
print(L)
# ---> [1, 2, 3, 4, 5, 6]
# Outer loop から書けばいいのだ
# ちなみに,list comprehension じゃないけど
print(sum(matrix, []))
# ---> [1, 2, 3, 4, 5, 6]
###############################
a = [(x, x**2) for x in range(5)]
print(a)
# ---> [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
from math import pi
b = [str(round(pi, i)) for i in range(1, 6)]
print(b)
# ---> ['3.1', '3.14', '3.142', '3.1416', '3.14159']
# 偶数だけ *100にしたい時
c = [x if x % 2 else x * 100 for x in range(1, 10)]
print(c)
# ---> [1, 200, 3, 400, 5, 600, 7, 800, 9]
##############################################
y = [100, 200, 300, 301, 5]
# 2で割り切れて、なおかつ10の倍数である
x = [x for x in y if not x % 2 and not x % 10]
print(x)
# ---> [100, 200, 300]
x2 = [x for x in y if x % 2 == 0 if x % 10 == 0]
print(x2)
# ---> [100, 200, 300]
# 2か5で割り切れる
z = [x for x in y if not x % 2 or not x % 5]
print(x)
# ---> [100, 200, 300, 5]
##############################################
# nested listを作りたい
matrix = [[0 for col in range(4)] for row in range(3)]
print(matrix)
# ---> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
lambda
add = lambda x, y: x + y
print(add(5,3))
# ---> 8
print((lambda x, y: x + y)(5, 3))
# ---> 8
enumerate
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(enumerate(seasons)) # this returns the address of the object
# ---> <enumerate object at 0x10418da68>
print(list(enumerate(seasons))) # display list of tuples of each item
# ---> [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
print(list(enumerate(seasons, 10)))
# ---> [(10, 'Spring'), (11, 'Summer'), (12, 'Fall'), (13, 'Winter')]
###############################################3
mylist = ["Wow","This","Awesome"]
for index, item in enumerate(mylist):
print(index, item)
# ---> 0 Wow
# 1 This
# 2 Awesome
datetime
import datetime
# 現在の時刻
print("RIGHT NOW IS:", datetime.datetime.now())
# ---> RIGHT NOW IS: 2018-10-23 01:24:33.761917
print(datetime.date(2019, 8, 12))
# ---> 2019-08-12
today = datetime.date.today() #今日の日付 現時点2018-10-23
tdelta = datetime.timedelta(days=7)
print("A week from today is: ", today + tdelta)
#---> A week from today is: 2018-10-30
# 今日から7日後の日付
print("A week before from today is: ", today - tdelta)
# ---> A week before from today is: 2018-10-16
# 一週間前の日付
Merging two dictionaries
# 2つ以上のdictionariesを1つにまとめる
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
# ---> {'a': 1, 'b': 3, 'c': 4}
pprint
from pprint import pprint
ugly = [(i, {'0': 'This',
'1': 'Makes',
'2': 'So',
'3': 'Much',
'4': 'Easier',
'5': 'To',
'6': 'Read!'
})
for i in range(3)
]
pprint(ugly)
# --->
[(0,
{'0': 'This',
'1': 'Makes',
'2': 'So',
'3': 'Much',
'4': 'Easier',
'5': 'To',
'6': 'Read!'}),
(1,
{'0': 'This',
'1': 'Makes',
'2': 'So',
'3': 'Much',
'4': 'Easier',
'5': 'To',
'6': 'Read!'}),
(2,
{'0': 'This',
'1': 'Makes',
'2': 'So',
'3': 'Much',
'4': 'Easier',
'5': 'To',
'6': 'Read!'})]
print(ugly)
# --->
[(0, {'0': 'This', '1': 'Makes', '2': 'So', '3': 'Much', '4': 'Easier', '5': 'To', '6': 'Read!'}), (1, {'0': 'This', '1': 'Makes', '2': 'So', '3': 'Much', '4': 'Easier', '5': 'To', '6': 'Read!'}), (2, {'0': 'This', '1': 'Makes', '2': 'So', '3': 'Much', '4': 'Easier', '5': 'To', '6': 'Read!'})]
sys
# どのpython versionを使っているのか知りたい時
import sys
print("Current Python version: ", sys.version)
# ---> Current Python version: 3.6.5
# Recursion のリミットを変えたい(Default = 1000)
x=1001
print(sys.getrecursionlimit())
# ---> 1000
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
# ---> 1001
Python do and don't
if statements
# Do this
if n in [1,2,3]:
print(n)
# Don't
if n==1 or n==2 or n==3:
print(n)
# elseをfor/while loop直後に書かない
for i in range(1):
print("looping")
else:
print("ELSE BLOCK")
# --->
# looping
# ELSE BLOCK
# breakがはいるとelse文は出力されない
for i in range(5):
print(i)
break
else:
print("ELSE BLOCK IS NOT PRINTED")
# --->
# 0
underscore _
a, _, b = (1, 2, 3)
print(a, b)
# ---> 1, 3
a, *_, b, c = (1, 2, 3, 4, 5, 6)
print(a, b, c)
# ---> 1, 5, 6
print(*_)
# ---> 2,3,4
infinity
my_inf = float('Inf')
print(99999999 > my_inf)
# ---> False
my_neg_inf = float('-Inf')
my_neg_inf > -99999999
# ---> False
def f(x, l=[]):
for i in range(x):
l.append(i * i)
print(l)
f(2)
# ---> [0, 1]
f(3, [3, 2, 1])
# ---> [3, 2, 1, 0, 1, 4]
f(3)
# ---> [0, 1, 0, 1, 4]
# Why the third call not [0,1,4]? なぜならfirst callのメモリーを使っているから
そんなんいつ使うんや
emoji : https://pypi.org/project/emoji/
- 絵文字も表せちゃうんです
pip install emoji
from emoji import emojize
print(emojize(":thumbs_up:"))
# ---> 👍
print(emoji.demojize('Python is 👍'))
# ---> Python is :thumbs_up:
print(emoji.emojize(':alien:'))
# ---> 👽
PrettyTable: https://pypi.org/project/PrettyTable
- テーブルをプリチーにしてくれる
from prettytable import PrettyTable
table = PrettyTable(['programming language', 'awesomeness'])
table.add_row(['Python', '100'])
table.add_row(['C++', '99'])
table.add_row(['Java', '80'])
table.add_row(['PHP', '40'])
print(table)
# --->
+----------------------+-------------+
| programming language | awesomeness |
+----------------------+-------------+
| Python | 100 |
| C++ | 99 |
| Java | 80 |
| PHP | 40 |
+----------------------+-------------+
wikipedia: https://wikipedia.readthedocs.io/en/latest/quickstart.html
pip install wikipedia
import wikipedia
result = wikipedia.page('tsunami')
print(result.summary)
# --->
# A tsunami (from Japanese: 津波, "harbour wave";
# English pronunciation: soo-NAH-mee) or tidal wave, also known as a seismic sea
# wave, is a series of waves in a water body caused by the displacement of a large
# volume of water, generally in an ocean or a large lake. Earthquakes, volcanic #
# eruptions and other underwater explosions (including detonations of underwater
# nuclear devices),...
print(wikipedia.search("Barack"))
# ---> ['Barack Obama', 'Barack Obama Sr.', 'Family of Barack Obama', 'List of things named after Barack Obama', 'List of federal judges appointed by Barack Obama', 'Barack Obama citizenship conspiracy theories', 'Barack Obama Supreme Court candidates', 'Timeline of the presidency of Barack Obama (2009)', 'Barack (brandy)', 'Protests against Barack Obama']
Snowballstemmer: https://github.com/shibukawa/snowball_py
import snowballstemmer
stemmer = snowballstemmer.stemmer('english');
print(type(stemmer))
# ---> <class 'snowballstemmer.english_stemmer.EnglishStemmer'>
print(stemmer.stemWords("We are the world".split()));
# ---> ['We', 'are', 'the', 'world']
from snowballstemmer import EnglishStemmer, SpanishStemmer
print(EnglishStemmer().stemWord("Gregory"))
# ---> Gregori
Calendar
import calendar
cal = calendar.month(2018, 9)
print(cal)
# --->
September 2018
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
hello
import __hello__
# ---> Hello World!
import this
- ZEN of python
import this
# --->
# 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!
Colorama:https://pypi.org/project/colorama/
- コードをカラフルにしましょう
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
# --->
その他おすすめ (のち追加)
FuzzyWuzzy: https://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/
pip install fuzzywuzzy
from fuzzywuzzy import fuzz
# 比較対象の文字列がどのくらい似ているかの比率
print(fuzz.ratio("this is a test", "this is a test!"))
# ---> 97
fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
# ---> 100
書かなかったけどこれも知っとけっていう私的module, libraris達
- OS
- request
- beautiful soup
- pygal
- pygame
- time
- json
- sys
- itertools
- re
最近習いたいmodule, library達
- pillow
- tensorflow
- pandas
- numpy
- matplotlib
- csv
- scrapy
- pyQT
- nltk
- pytorch
- keras
とか、まあその他諸々いっぱいありすぎる。
QUIZ
- ここまで読んだそこのあなた!今こそ得た知識を脳フル回転して使うべき!
- てな訳で、以下はネットで見つけたpython tricksたちをクイズにしたもの(それぞれ原文リンク載せとくので参考に
- まずはパソコンでビルドせずに紙に書くなりして、何をアウトプットするか考えて見てね
Question 1: Python Interview Question FizzBuzz
# Q: What will this prints out??
print(' '.join(['FizzBuzz' if not(i % 3 or i % 5) else 'Fizz' if not i % 3 else 'Buzz' if not i % 5 else str(i) for i in range(1, 21)]))
# ただし実際にlist comprehensionを使う時は長くなりすぎぬよう気をつけよう
Question 2: next() function for iterator object
my_list = [1, 3, 6, 10]
a = (x**2 for x in my_list)
print(next(a), next(a))
Question 3: Decorator
def Foo(n):
def multiplier(x):
return x * n
return multiplier
a = Foo(5)
b = Foo(5)
print(a(b(2)))