2021-03-13に投稿

Python 組み込み関数

読了目安:20分

Pythonで用意されている組み込み関数の説明です。

abs(x) 絶対値

abs(-1.23)  # => 1.23
abs(3 + 4j) # => 5.0

all(iterable) 要素が全て真ならTrue、空ならTrue

all([]) # => True
all([1, 2, 3, 4, 5]) # => True
all([0, 1, 2, 3, 4]) # => False
all(["a", "b", "c"]) # => True
all(["a", "", "c"]) # => False
all(["a", None, "c"]) # => False

any(iterable) 要素のいずれかが真ならTrue、空ならFalse

any([]) # => False
any([0, 1, 2, 3, 4]) # => True
any([0, 0, 0]) # => False
any(["", None, "X"]) # => True
any(["", None, 0]) # => False

ascii(object) エスケープされた印字可能文字列

ascii("abc⚡de") # => "'abc\\u26a1de'"

bin(x) 2進数文字列

bin(10) # => '0b1010'

bool([x]) ブール値変換

bool() # => False
bool(None) # => False
bool(False) # => False
bool(0) # => False
bool(0.0) # => False
bool(0j) # => False

from decimal import Decimal
bool(Decimal(0)) # => False

from fractions import Fraction
bool(Fraction(0, 1)) # => False

bool('') # => False
bool(()) # => False
bool([]) # => False
bool({}) # => False
bool(set()) # => False
bool(range(0)) # => False

bool('0') # => True
bool('1') # => True
bool('A') # => True
bool(1) # => True

breakpoint(*args, **kws) デバッガの呼び出し

def func():
    breakpoint()
    n = 1
    n = n + 1
    return

if __name__ == "__main__":
    func()

上記スクリプトの実行でpdb(Pythonデバッガ)が呼び出される。
コマンドn等でステップで追える。

bytearray([source[, encoding[, errors]]])

# バイト列リテラルからバイト配列を作成
bytearray(b'xyz') # => bytearray(b'xyz')

# 文字列をencode()でバイト配列に変換して作成
bytearray("abc", "utf8") # => bytearray(b'abc')

# 整数を指定するとそのサイズでnullバイトのバイト配列が作成
bytearray(5) # => bytearray(b'\x00\x00\x00\x00\x00')

# 整数値範囲のイテラブルからバイト配列を作成
bytearray(x+65 for x in range(5)) # => bytearray(b'ABCDE')

bytes([source[, encoding[, errors]]]) バイトのイミュータブルなシーケンス

# バイト列リテラルからバイト配列を作成
bytes(b'xyz') # => b'xyz'

# 文字列をencode()でバイト配列に変換して作成
bytes("abc", "utf8") # => b'abc'

# 整数を指定するとそのサイズでnullバイトのバイト配列が作成
bytes(5) # => b'\x00\x00\x00\x00\x00'

# 整数値範囲のイテラブルからバイト配列を作成
bytes(x+65 for x in range(5)) # b'ABCDE'

callable(object) 呼び出し可能なオブジェクトならTrue

def f(a, b):
    return a + b

v = 1
x = f
callable(v) # => False
callable(x) # => True

chr(i) 整数値を文字列に

chr(0x1F40D) # => '🐍'

classmethod クラスメソッドを定義するデコレータ

class SampleClass:

    @classmethod
    def class_method(cls, n):
        print(cls, n)

sc = SampleClass()
sc.class_method('a') # => <class '__main__.SampleClass'> a
SampleClass.class_method('b') # => <class '__main__.SampleClass'> b

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) コード片のコンパイル

modeはコンパイルするコードの種類を指定する。

  • exec 複数行の文
  • eval 単一式の評価
  • single 単一文
sourcre = '''
x = 123
y = "abc"
print(x, y)
'''
codeobj = compile(sourcre, 'fileName', 'exec')
exec(codeobj) # => 123 abc
codeobj = compile("1 + 2", 'fileName', 'eval')
eval(codeobj) # => 3
a = "abc"
codeobj = compile('a += "123"', 'fileName', 'single')
exec(codeobj)
a # => abc123

complex([real[, imag]]) 複素数

complex() # => (0j)
complex("1+2j") # => (1+2j)
complex(1) # => (1+0j)
complex(1.1, 2.2) # => (1.1+2.2j)

delattr(object, name) 属性の削除

class SampleClass:
    pass

sc = SampleClass()
sc.val = 1
print(sc.val) #=> 1
delattr(sc,"val")
print(sc.val) # => AttributeError: val

dict(**kwarg), dict(mapping, **kwarg), dict(iterable, **kwarg) 辞書

dic1 = dict(a=1, b=2, c=3)
dic2 = dict({'a':1, 'b':2, 'c':3})
dic3 = dict({ chr(x + 97) : x + 1 for x in range(3)})
dic4 = dict({'a':1, 'c':3}, b=2)
dic5 = dict({ chr(x + 97) : x + 1 for x in range(2)},c=3)
dic6 = {'a':1, 'b':2, 'c':3}
dic7 = { chr(x + 97) : x + 1 for x in range(3)}
dic1 == dic2 == dic3 == dic4 == dic5 == dic6 == dic7 # => True

dir(object) 名前や属性のリスト

引数なしの場合、現在のスコープで有効な名前のリストを取得する。

abc = 1
dir()
# =&gt; ['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', 'abc', 'exit', 'get_ipython', 'os', 'quit', 'sys']
class SampleClassBase:
    class_variable_1 = 1
    def __init__(self, name=""):
        self.name = name

class SampleClass(SampleClassBase):
    class_variable_2 = 1
    def __init__(self, name="", age=0):
        super().__init__(name)
        self.age = age

scb = SampleClassBase()
dir(scb)
# =&gt; ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'class_variable_1', 'name']
sc = SampleClass()
dir(sc)
# =&gt; ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'class_variable_1', 'class_variable_2', 'name']

divmod(a, b) 商と剰余

a, b = divmod(10, 3) # => a=3, b=1
a, b = divmod(10.0, 3.5) #=> a=2.0, b=3.0

enumerate(iterable, start=0) enumerate オブジェクト

インデックスとイテレーショで得られる要素の組を取得する。

array = ['a', 'b', 'c', 'd']
for i, item in enumerate(array):
    print(i, item) # => 0 a 1 b 2 c 3 d

for i, item in enumerate(array, 2):
    print(i, item) # => 2 a 3 b 4 c 5 d

eval(expression[, globals[, locals]]) 式の実行

a = 1
b = eval('a+1') #=> 2

exec(object[, globals[, locals]]) 文の実行

compile コード片のコンパイル

sourcre = '''
x = 123
y = "abc"
print(x, y)
'''
codeobj = compile(sourcre, 'fileName', 'exec')
exec(codeobj) # => 123 abc

filter(function, iterable) フィルタ

array = [1, 2, 3, 4, 5, 6, 7]
filterd = filter(lambda x: x%2 == 0, array)
# 以下と同じfilterd = (x for x in array if x%2 == 0)
list(filterd) #=> [2, 4, 6]

float([x]) 浮動小数点

float() # => 0.0
float("1.23") # => 1.23
float("-1.23E10") # => -12300000000.0
float("Infinity") # => inf
float("-inf") # => -inf
float("nan") # => nan

format(value[, format_spec]) フォーマット文字列

format(12,"0>8b")
# =&gt; 00001100

frozenset([iterable]) イミュータブルな順序なし集合

frozenset() #=> frozenset() 
frozenset({'a', 'c', 'a'}) # => frozenset({'a', 'c'})
frozenset(['a', 'c', 'a']) # => frozenset({'a', 'c'})
frozenset({chr(x + 97) for x in range(3) if x != 1}) # => frozenset({'a', 'c'})

getattr(object, name[, default]) 属性の取得

class SampleClass:
    def __init__(self, name):
        self.name = name

sc = SampleClass("taro")
getattr(sc,"name") # => taro
getattr(sc,"num", 0) # => 0

globals グローバルシンボルテーブル

globals()

hasattr(object, name) 属性の存在

class SampleClass:
    def __init__(self, name):
        self.name = name

sc = SampleClass("taro")
hasattr(sc, "name") # => True
hasattr(sc, "num") # => False

hash(object) ハッシュ値

hash("a") #=> 7562440111937489460

help([object]) ヘルプ

help() # 対話的な使用

hex(x) 16進数

hex(255) #=> 0xff

id オブジェクトの識別子

class SampleClass:
    pass

sc = SampleClass()
id(sc) # => 1479001398408

input 標準出力読み込み

s = input('input string!')
print(s)  

int([x]), int(x, base=10) 整数値

int() # => 0
int(1) # => 1
int(2.5) # => 2
int("100", 2) # => 4
int("F0", 16) # => 240

isinstance(object, classinfo) 指定したクラスのインスタンスか

isinstance("abc", str) # => True
isinstance("abc", (str, int)) # => True
isinstance("abc", (float, int)) # => False
class SampleClassBase:
    pass

class SampleClass(SampleClassBase):
    pass

scb = SampleClassBase()
sc = SampleClass()
isinstance(scb, SampleClassBase) # => True
isinstance(scb, SampleClass) # => False
isinstance(sc, SampleClassBase) # => True
isinstance(sc, SampleClass) # => True

issubclass(class, classinfo) サブクラス判定

class SampleClassBase:
    pass

class SampleClass(SampleClassBase):
    pass

scb = SampleClassBase()
sc = SampleClass()
issubclass(SampleClassBase, SampleClassBase) # => True
issubclass(SampleClassBase, SampleClass) # => False
issubclass(SampleClass, SampleClassBase) # => True
issubclass(SampleClass, SampleClass) # => True

iter(object[, sentinel])

items = [1, 2, 3, 4, 5]
it = iter(items)
while True:
    try:
        item = next(it)
        print(item)
    except StopIteration:
        break

len(s) オブジェクトの長さ・サイズ

len("abc") # => 3
len(b"abc") # => 3
len((1, 2, 3)) # => 3
len([1, 2, 3]) # => 3
len(range(3)) # => 3

list([iterable]) リスト

items = list([1, 2, 3, 4, 5])
items = list((1, 2, 3, 4, 5))
items = list(x+1 for x in range(5))

locals ローカルシンボルテーブル

locals()

map map(function, iterable, ...) マップ

list(map(lambda x: x * x , [1, 2, 3])) # => [1, 4, 9]
list(map(lambda x,y: x * y , [1, 2, 3, 4], [10, 20, 30])) # => [10, 40, 90]

max(iterable, *[, key, default]),max(arg1, arg2, *args[, key]) 最大値

max(3, 2) # => 3
max(1, 5, 3) # => 5
max([1, 2, 3, 4, 5]) # => 5
max([1, 2, 3, 4, 5], default=0) # => 5
max([], default=0) # => 0
max([]) # => ValueError: max() arg is an empty sequence

memoryview メモリビュー

view = memoryview(b'abc')
for item in view:
    print(item) # => 97 98 99

min(iterable, *[, key, default]), min(arg1, arg2, *args[, key]) 最小値

min(3, 2) # => 2
min(1, 5, 3) # => 1
min([1, 2, 3, 4, 5]) # => 1
min([1, 2, 3, 4, 5], default=0) # => 1
min([], default=0) # => 0
min([]) # => ValueError: min() arg is an empty sequence

next(iterator[, default]) イテレータの次

it = iter([1, 2, 3])
print(next(it)) # => 1
print(next(it)) # => 2
print(next(it)) # => 3
print(next(it, -1)) # => -1
# print(next(it)) # =&gt; StopIteration: 

object 全てのクラスの既定objcectクラスのインスタンス

obj = object()

oct(x) 8進文字列

oct(10) => '0o12'

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) ファイルオープン

with open('.sample.txt', mode='w', encoding='utf-8') as f:
    f.write('あいうえお')

with open('.sample.txt', mode='r', encoding='utf-8') as f:
    print(f.read()) # => あいうえお

with open('.sample.txt', mode='a', encoding='utf-8') as f:
    f.write('あいうえお')

with open('.sample.txt', mode='r', encoding='utf-8') as f:
    print(f.read())# => あいうえおあいうえお

ord(c) Unicode コードポイント

ord('🐍') # => 128013

pow(base, exp[, mod]) べき乗

pow(2, 10) # => 1024    2**10
pow(2, 10 , 100) # => 24   2**10 % 100

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) 出力

print(1, 2, 3) # => 1 2 3
print(1, 2, 3, sep="-") # => 1-2-3
print(1, 2, 3, sep="=",end="\n----\n") # => 1=2=3\n----
with open('.sample.txt', mode='w', encoding='utf-8') as f:
    print(1, 2, 3 , file=f)

with open('.sample.txt', mode='r', encoding='utf-8') as f:
    print(f.read()) # => 1 2 3

class property(fget=None, fset=None, fdel=None, doc=None) プロパティ

class SampleClass:
    def __init__(self):
        self._name = None

    def get_name(self):
        return self._name

    def set_name(self, value):
        self._name = value

    def del_name(self):
        del self._name

    name = property(get_name, set_name, del_name, "name property")

デコレータ@propertyで読取専用のプロパティを定義できる。

class SampleClass:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

sc = SampleClass("taro")
sc.name # => taro

setter,deleterもデコレートできる。

class SampleClass:
    def __init__(self):
        self._name = None

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    @name.deleter
    def name(self):
        del self._name

sc = SampleClass()
sc.name = "taro"
print(sc.name) # => taro

range(stop),range(start, stop[, step]) 範囲の数値

  • range(終了する数値) 0から終了する数値-1までの整数
  • range(開始数値, 終了する数値) 開始数値から終了する数値-1までの整数
  • range(開始数値, 終了する数値, ステップ) 開始数値から終了する数値-1までの整数をステップ数刻み
for i in range(5):
    print(i)
#=> 0 1 2 3 4

for i in range(2, 12):
    print(i)
#=> 2 3 4 5 6 7 8 9 10 11

for i in range(2, 12, 4):
    print(i)
#=> 2 6 10

repr(object) 印字可能な文字列

repr(1) # => 1
repr([1, 2, 3]) # => [1, 2, 3]

reversed(seq) 逆順のイテレータ

list(reversed("abc")) # => ['c', 'b', 'a']
list(reversed([1, 2, 3])) # => [3, 2, 1]
list(reversed(range(3, 8, 2))) # => [7, 5, 3]

round(number[, ndigits]) 数値のまるめ

round(123.456789,2) # => 123.46
round(123.456789,1) # => 123.45
round(123.456789,0) # => 123.0
round(123.456789,-1) # => 120.0
round(123.456789,-2) # => 100.0

set([iterable]) 集合

set() #=> set() 
set({'a', 'c', 'a'}) # => set({'a', 'c'})
set(['a', 'c', 'a']) # => set({'a', 'c'})
set({chr(x + 97) for x in range(3) if x != 1}) # => set({'a', 'c'})

setattr(object, name, value) 属性の設定

class SampleClass:
    def __init__(self, name=""):
        self.name = name
sc = SampleClass()
setattr(sc, "name", "taro")
sc.name #=> taro

slice(stop),slice(start, stop[, step]) スライスのインデックス集合

items = ["a", "b", "c", "d", "e", "f", "g"]
items[slice(3)] # => ['a', 'b', 'c'] items[:3]と同じ
items[slice(2, 6, 3)] # => ['c', 'f'] items[2:6:3]と同じ

sorted(iterable, *, key=None, reverse=False) ソートしたリスト

items = ["a", "b", "A", "c", "B", "C"]
sorted(items) # => ['A', 'B', 'C', 'a', 'b', 'c']
sorted(items,key=str.lower) # => ['a', 'A', 'b', 'B', 'c', 'C']
sorted(items,key=lambda x: ord(x)) # => ['A', 'B', 'C', 'a', 'b', 'c']

staticmethod 静的メソッド

class StaticClassSample:
    @staticmethod
    def static_method(n):
        print(n)

scs = StaticClassSample()
scs.static_method(1) # => 1
StaticClassSample.static_method(2) # => 2

str(object=''), str(object=b'', encoding='utf-8', errors='strict') 文字列

str(123) # => '123'

sum(iterable, /, start=0) 合計

sum([1, 2, 3, 4]) # => 10
sum(x**2 for x in range(4)) # => 14
sum([1, 2, 3, 4], 100) # => 110

super([type[, object-or-type]]) 親

class SampleClassBase:
    def __init__(self, name=""):
        self.name = name
    def print_name(self):
        print(self.name)

class SampleClass(SampleClassBase):
    def __init__(self, name="", age=0):
        super().__init__(name)
        self.age = age
    def print_name_age(self):
        super().print_name()
        print(self.age)

sc = SampleClass("taro", 12)
sc.print_name_age() # => taro 12

tuple([iterable]) タプル

tuple([1, 2, 3]) # => (1, 2, 3)
tuple((1, 2, 3)) # => (1, 2, 3)
tuple(range(1,4)) # => (1, 2, 3)

type(object) 型

type("abc") is str # => True
type(123) is int # => True

class SampleClassBase:
    pass

class SampleClass(SampleClassBase):
    pass

sc = SampleClass()
type(sc) is SampleClass # => True
type(sc) is SampleClassBase # => False

vars([object]) __dict__ 属性

vars()

zip(*iterables) 複数イテラブルを集める

items1 = [1, 2, 3, 4]
items2 = ["a", "b", "c"]

zipped = zip(items1, items2)

items = list(zipped) # => [(1, 'a'), (2, 'b'), (3, 'c')]

for x, y in zip(items1, items2):
    print(x, y) # => 1 a 2 b 3 c

__import__(name, globals=None, locals=None, fromlist=(), level=0) インポート

importで呼び出される関数。

Originally published at marusankakusikaku.jp
ツイッターでシェア
みんなに共有、忘れないようにメモ

maru3kaku4kaku

Pythonこつこつ学習中。よく忘れる。

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント