LoginSignup
415

More than 5 years have passed since last update.

覚えておくと便利!Python標準ライブラリ10選

Last updated at Posted at 2014-11-15

Pythonで,知っておくとちょっと便利になる組み込み関数や標準ライブラリを紹介してみようと思います! そこそこメジャーなものからニッチなものまでいろいろありますが,知らないものはぜひチェックしてみて下さい.

組み込み関数

allとany

all( )は引数の要素が全てTrueならばTrue,any( )は引数の要素のいずれか1つでもTrueならTrueを返す.

In [1]: all(_ % 2 == 0 for _ in [1, 2, 3]) # 全て偶数 or not
Out[1]: False

In [2]: any(_ % 2 == 0 for _ in [1, 2, 3]) # いずれか1つでも偶数 or not
Out[2]: True

divmod

商と余りを1度に求めてくれる.

In [1]: 10 // 3, 10 % 3 # 商と余りを求める
Out[1]: (3, 1)

In [2]: divmod(10, 3) # 上記と全く同じ
Out[2]: (3, 1)

collections

Counter.most_common

iterable内で出現頻度が高い順にソートしてくれる.文中で1番使われている単語とか一瞬で求まる.

In [1]: from collections import Counter

In [2]: Counter(['a', 'b', 'c', 'a', 'b', 'a']).most_common()
Out[2]: [('a', 3), ('b', 2), ('c', 1)]

namedtuple

バリューオブジェクトを作成する.複数の属性を持たせたい時に便利.

In [1]: from collections import namedtuple

In [2]: Doc = namedtuple('Doc', 'tf idf')

In [3]: doc = Doc(tf=0.1, idf=0.01)

In [4]: doc.tf, doc.idf
Out[4]: (0.1, 0.01)

OrderedDict

通常のdictは挿入した順番を維持しないが,OrderedDictは維持してくれる.

In [1]: from collections import OrderedDict

In [2]: d = OrderedDict((('a', 1), ('b', 2), ('c', 3))) # OrderedDict(a=1, b=2, c=3) だと維持されないので注意

In [3]: d['d'] = 4 # 最後に追加される

In [4]: for k, v in d.iteritems(): print k, v # 挿入した順にprint
a 1
b 2
c 3
d 4

math

fsum

iterable内の値の総和を桁落ちせずに求めてくれる.

In [1]: import math

In [2]: sum([.1] * 10) # 桁落ちしてしまう
Out[2]: 0.9999999999999999

In [3]: math.fsum([.1] * 10)
Out[3]: 1.0

log10

常用対数の時は log(x, 10) でなく log10(x) を用いる方が高精度.

In [1]: import math

In [2]: math.log(5, 10)
Out[2]: 0.6989700043360187

In [3]: math.log10(5) # 上記と同じだがこちらの方が高精度
Out[3]: 0.6989700043360189

fileinput

複数のファイルを1度にまとめて処理することができる.ファイルを指定しなければ標準入力を読み込む.

abc.txt
a b c
def.txt
d e f
fileinput.py
import fileinput
for l in fileinput.input():
  print l 
$ python fileinput.py abc.txt def.txt # 複数のファイルを1度に読み込む
a b c
d e f
$ cat abc.txt | python fileinput.py # 標準入力
a b c

ConfigParser

configファイルを読み込み,いい感じにパースしてくれる.

.gitconfig(一部)
[user]
name = Hoge
email = hoge@example.com
[color]
ui = auto
diff = auto
status = auto
interactive = auto
branch = auto
grep = auto
configparser.py
import ConfigParser
cfg = ConfigParser.SafeConfigParser()
cfg.read('.gitconfig')

for sec in cfg.sections():
    print '[{}]'.format(sec)
    for opt in cfg.options(sec):
      print '{} : {}'.format(opt, cfg.get(sec, opt))
$ python configparser.py
[user]
name : Hoge
email : hoge@example.com
[color]
ui : auto
diff : auto
status : auto
interactive : auto
branch : auto
grep : auto

shlex.split

字句解析をし,いい感じに分割してくれる.str.splitと違い,引用符で囲まれた部分を1つにしてくれる.

In [1]: import shlex

In [2]: '''he said 'you are beautiful!' '''.split() # ' '内が分割される
Out[2]: ['he', 'said', "'you", 'are', "beautiful!'"]

In [3]: shlex.split('''he said 'you are beautiful!' ''') # ' '内がまとまる!
Out[3]: ['he', 'said', 'you are beautiful!']

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
415