開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のII部(ビルトインオブジェクト) 9章のまとめ演習6(ディクショナリのインデクシング)、7(オブジェクトの操作に関する質問)、8(文字列のインデクシング)を解いてみる。
6.
ディクショナリで存在しないキーを指定してインデクシングを行うと、エラーが発生する。リストでも同様に存在しないキーを指定するとエラーが発生する。
ディクショナリで存在しないキーソ指定して値の代入を行うと、新しいキーと値がディクショナリに追加される。リストの場合は存在しないオフセットを指定して値を代入しようとするとエラーが発生する。
7.
+演算子で型の異なるオブジェクトを連結しようとすると、エラーが発生する。
+演算子は、オペランドの少なくとも一方がディクショナリである場合に正しく機能しない。
appendメソッドはリストと文字列のうち、リストに使用できるメソッド。
keysメソッドはリストに使用できない。
リスト、文字列に対してスライシングや連結の操作を行った場合、戻り値として得られるオブジェクトそそれぞれリスト、文字列。
8.
4文字からなる文字列S("spam")を作成し、S[0][0][0][0][0]というコードを実行した結果は文字列's'が返される。
また、S[0][0][0][0][0]というインデクシングのコードは['s','p','a','m']というリストに対しても使える。理由はリストの要素が文字列だから。(リストであってもインデクシング出来ない変数、数値等の場合は同様の操作はエラーになる。)
確認。
入出力結果(Terminal)
$ python Python 2.7.2 (default, Feb 12 2012, 23:50:38) [GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> D={'a':1,'b':2,'c':3} >>> D['d'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'd' >>> L=['a','b','c'] >>> L[4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range >>> D['d']=4 >>> D {'a': 1, 'c': 3, 'b': 2, 'd': 4} >>> L[3]='d' Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range >>> 'python'+[1,2,3] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'list' objects >>> [1,2,3]+(4,5,6) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "tuple") to list >>> {'a':1,'b':2}+{'c':3,'d':4} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'dict' and 'dict' >>> D+1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'dict' and 'int' >>> L.append('d') >>> L ['a', 'b', 'c', 'd'] >>> 'python'.append('a') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'append' >>> L.keys() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'keys' >>> ['a','b','c','d','e'][2:4] ['c', 'd'] >>> 'python'[2;4] File "<stdin>", line 1 'python'[2;4] ^ SyntaxError: invalid syntax >>> 'python'[2:4] 'th' >>> S='spam' >>> S[0][0][0][0][0] 's' >>> S=['s','p','a','m'] >>> S[0][0][0][0][0] 's' >>> quit() $
0 コメント:
コメントを投稿