「大人の教養・知識・気付き」を伸ばすブログ

一流の大人(ビジネスマン、政治家、リーダー…)として知っておきたい、教養・社会動向を意外なところから取り上げ学ぶことで“気付く力”を伸ばすブログです。データ分析・語学に力点を置いています。 →現在、コンサルタントの雛になるべく、少しずつ勉強中です(※2024年1月21日改訂)。

MENU

Pythonをゆっくりていねいに学ぶ(その11/X)

 Pythonを真面目にゆっくり学ぶべく

を参考に学んでいきます*1

5. Pyの化粧箱:モジュール、パッケージ、プログラム

 \mathrm{Python}で現実的な大規模プログラムを書くための方法を学ぶ。

5.2 パッケージ

 \mathrm{Python}アプリケーションを大規模にするために、モジュールはパッケージと呼ばれる階層構造に組織することができる。

# メインプログラム:boxes/weather.py
from sources import daily, weekly

print("Daily forecast:", daily.forecast())
print("Weekly forecast:")
for number, outlook in enumerate( weekly.forecast(),1):
    print(number, outlook)

# モジュール1:boxes/sources/daily.py
def forecast():
    return 'like yesterday'

# モジュール2:boxes/sources/weekly.py
def forecast():
    return ['snow','more snow','sleet','freezing rain','rain','fog','hail']

5.3 Python標準ライブラリ

 \mathrm{Python}には標準ライブラリがあり、コア言語が膨れ上がるのを防ぐべく別に管理されている。

5.3.1 setdefault()とdefaultdict()による存在しないキーのアクセス

 辞書に対して存在しないキーでアクセスすると例外が生成される。例外を防ぐには\mathrm{get}()関数を用いるが、他に\mathrm{setdefault}()関数を用いると、もし存在しないキーでアクセスした場合にそのキーと予め別の引数で与えた値を新たに要素として追加する。

# setdefault()による値へのアクセス

periodic_table = {'Hydrogen':1, 'Helium':2}
print(periodic_table)

print('**************')

carbon = periodic_table.setdefault('Carbon', 12)
print(carbon)
print(periodic_table) # Carbonが追加されている

print('**************')

# 既存のものには何も変更しない
helium = periodic_table.setdefault('Helium',947)
print(helium)


### defaultdict
# 新しいキーに対して予めデフォルト値を与えておく

from collections import defaultdict

periodic_table = defaultdict(int)

periodic_table['Hydrogen'] = 1

print(periodic_table['Lead'])
print(periodic_table['sodium'])

print(periodic_table)
5.3.2 Counter()による要素数の計算
# Counter
from collections import Counter
breakfast = ['spam', 'spam', 'eggs', 'spam']
breakfast_counter = Counter(breakfast)

# most_common():全ての要素を降順で返す
breakfast_counter.most_common()
breakfast_counter.most_common(1)

# counterは各種演算子で結合できる
lunch = ['eggs','eggs','bacon']
lunch_counter = Counter(lunch)

print(breakfast_counter + lunch_counter)
print(breakfast_counter - lunch_counter)
print(breakfast_counter & lunch_counter)
print(breakfast_counter | lunch_counter) # 和集合だと共通する要素の数はより多い方を採用する
5.3.3 OrderedDict()によるキー順のソート
# OrderedDict()辞書のキーに順序を与える
from collections import OrderedDict
quotes = OrderedDict([
    ('Moe','A wise guy, huh?'),
    ('Larry','Ow!'),
    ('Curly', 'Nyuk nyuk!'),
])

for stooge in quotes:
    print(stooge)

*1:第2版が出ているものの初版しか持っていないのでこちらで。

プライバシーポリシー お問い合わせ