開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のIV部(関数)のまとめ演習6.(ディクショナリの和集合)を解いてみる。
その他参考書籍
6.(ディクショナリの和集合)
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def addDict(a, b): res = {} for k, v in a.items(): res[k] = v for k, v in b.items(): res[k] = v return res print(addDict({'a':1,'b':2}, {'c':3,'d':4})) print(addDict({'a':1,'b':2}, {'b':3,'c':4})) # リストを指定すると例外発生 try: print(addDict([1,2],[3,4])) except Exception as err: print(err) # 本来は関数を作成しなくてもディクショナリのupdateメソッドを使えばいい d = {'a':1,'b':2} d.update({'c':3,'d':4}) print(d) d = {'a':1,'b':2} d.update({'b':3,'c':4}) print(d) def addDict1(a, b): if type(a) == type({'a':1}): return addDict(a, b) res = a + b return res for a, b in [({'a':1,'b':2}, {'c':3,'d':4}), (10, 20), ("python", "javascript"),([1,2],[3,4])]: print(addDict1(a, b))
入出力結果(Terminal)
$ ./sample.py {'d': 4, 'b': 2, 'c': 3, 'a': 1} {'b': 3, 'c': 4, 'a': 1} 'list' object has no attribute 'items' {'d': 4, 'b': 2, 'c': 3, 'a': 1} {'b': 3, 'c': 4, 'a': 1} {'d': 4, 'b': 2, 'c': 3, 'a': 1} 30 pythonjavascript [1, 2, 3, 4] $
0 コメント:
コメントを投稿