Python 3.1

一部だけメモ。Python 3.1b1でテスト。

Ordered Dictionaries

順序付き辞書が追加された。

>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od['a'] = 1
>>> od['b'] = 2
>>> od['c'] = 3
>>> od.items()
ItemsView(OrderedDict([('a', 1), ('b', 2), ('c', 3)]))
>>>
>>> d = {}
>>> d['a'] = 1
>>> d['b'] = 2
>>> d['c'] = 3
>>> d.items()
dict_items([('a', 1), ('c', 3), ('b', 2)])

Format Specifier for Thousands Separator

3桁ごとのカンマが付けられるようになった。

format(1234, '8d')   # '    1234'
format(1234, '08d')  # '00001234'
format(1234, '8,d')  # '   1,234'
format(1234, '08,d') # '0,001,234'
format(1234.5, '8.1f')   # '  1234.5'
format(1234.5, '8,.1f')  # ' 1,234.5'
format(1234.5, '8,.2f')  # '1,234.50'

Other Language Changes

  • bit_length()

ビット数を返すメソッドがintに追加された。

>>> getattr(int, 'bit_length')
<method 'bit_length' of 'int' objects>
>>> (37).bit_length()
6
>>> bin(37)
'0b100101'
  • format()

番号を省略した場合、自動的に順序付けされるようになった。

>>> 'foo = {0}, bar = {1}'.format(1, 'c')
'foo = 1, bar = c'
>>> 'foo = {}, bar = {}'.format(1, 'c')
'foo = 1, bar = c'
  • Counter
>>> from collections import Counter
>>> c = Counter(['foo', 'bar', 'foo', 'baz', 'bar', 'bar'])
>>> c
Counter({'bar': 3, 'foo': 2, 'baz': 1})
>>> c['foo']
2
>>> c.elements()
<itertools.chain object at 0x00C15B70>
>>> list(_)
['baz', 'foo', 'foo', 'bar', 'bar', 'bar']