2012年6月19日火曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のIII部(ステートメント)まとめ演習(ディクショナリのソート)3を解いてみる。

3.

コード(TextWrangler)

sample.py

#!/usr/bin/env python
#encoding: utf-8

d = {'a':1,'b':2,'c':3,'d':4,'e':5}
print("ディクショナリ")
for key in d.keys():
 print(key,str(d[key]),sep=":",end = ', ')
print("\nソート")
for key in sorted(d.keys()):
 print(key,d[key],sep=":",end = ', ')
print()

入出力結果(Terminal)

$ ./sample.py
ディクショナリ
a:1, c:3, b:2, e:5, d:4, 
ソート
a:1, b:2, c:3, d:4, e:5, 
$

ちなみにsortedだけじゃなくてsortも使ってみようと思ったけど、dict_keysオブジェクトっていうのがでてきてよく分からなくなった。。python3.xで何か変わったのかな〜

$ python
Python 3.2.3 (default, Apr 18 2012, 20:17:30) 
[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}
>>> d.keys()
dict_keys(['a', 'b'])
>>> sorted(d.keys())
['a', 'b']
>>> d.keys()
dict_keys(['a', 'b'])
>>> d.keys().sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict_keys' object has no attribute 'sort'
>>> l=[5,1,4,2,3]
>>> l.sort()
>>> l
[1, 2, 3, 4, 5]
>>> l=[5,1,4,2,3]
>>> sorted(l)
[1, 2, 3, 4, 5]
>>> l
[5, 1, 4, 2, 3]
>>> quit()

0 コメント:

コメントを投稿