0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python 関数の備忘録

Last updated at Posted at 2021-07-13

bin()

10進数を二進数にする時に使う。

print(bin(1))
print(bin(2))
print(bin(5))
print(bin(10))

# result
0b1
0b10
0b101
0b1010

出力結果の頭の0bは2進数であることを表しているだけのもの。

また、2進数をそのままprintで出力すると10進数として出力される。

num_bin = 0b1010

print(num_bin)

# result
10

count()

文字列のカウントに使う。

string.count(element, start, end)

stringはstring型の変数。
elementはカウントしたい要素。
startはスライスの位置の指定。オプションなので必須ではない。
endはカウントを止めるスライスの位置の指定。これもオプション。

string = "Hello World"

print(string.count("l"))
print(string.count("l", 1, -2))

# result
3
2

スタートを1に指定しているが、0からのスタートなので0番目の文字は"H"。
-2は後ろからのカウントとなるので-2番目は"l"。

Pythonでは場所を指定するとそれ以降、それ以前のものを指すことになるので実際には"llo Wor"の間でカウントをしていることになる。

str.rfind()

引数に指定した文字列がstrに含まれるとき、最大となるインデックスを返す。
つまり、一番最後に見つかった場所をインデックスで返す。
str.rfind()は次のような構造になる。

str.rfind(sub, start, end)

strは文字列。
startは検索対象の文字列のスライスのスタート位置。
endは検索対象の文字列のスライスのエンド位置。

a = "No pain, No gain."

print(a.rfind("No"))
print(a.rfind("i", 2, -3))

# result
9
5

map()

第一引数に関数、第二引数にシーケンス(リストやタプルなど)。
第二引数に指定されたものに含むそれぞれの値に対して、第一引数の処理を施すもの。
厳密には定義が違うらしいが、少々難解なので初学者の認識としてはこれで良いと思う。

l = ['Ryu', 'ken', 'Terry', 'Kazuya']

print(list(map(len, l)))

# result
[3, 3, 5, 6]

Python2でmap関数はリストを返していた。
Python3ではmapオブジェクトというイテレータを返す点に注意。

結果をリストにしたい場合はlist()を使う

l = [3.3, -6, 8]

print(map(int, l))
print(list(map(int, l)))

# result
<map object at 0x7ffedbfd5a30>
[3, -6, 8]

float()

引数に指定した数値や文字列から浮動小数点数を得るときに使う。

print(float(10))
print(float(1.1))
print(float())
print(float("3.14"))

# result
10.0
1.1
0.0
3.14

また、floatを用いると無限大を表現することができる。

float('inf')
0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?