キーが<= 10 ^ 9の数値で、値が数値のリストである辞書を実装しようとしています。
a=[]
for i in xrange(n):
h,j = raw_input().split()
b=int(h)
l=int(j)
a[b].append(l)
リスト インデックスが範囲外というエラーが表示されます。
キーが<= 10 ^ 9の数値で、値が数値のリストである辞書を実装しようとしています。
a=[]
for i in xrange(n):
h,j = raw_input().split()
b=int(h)
l=int(j)
a[b].append(l)
リスト インデックスが範囲外というエラーが表示されます。
ここで使用できcollections.defaultdict
ます:
In [15]: from collections import defaultdict
In [16]: dic=defaultdict(list)
In [17]: for _ in xrange(4):
....: h,j=map(int,raw_input().split())
....: dic[h].append(j)
....:
1 10
1 20
2 30
3 5
In [18]: dic
Out[18]: defaultdict(<type 'list'>, {1: [10, 20], 2: [30], 3: [5]})
または単純なdictを使用して使用しますdict.setdefault
:
In [19]: dic={} #use {} for declaring a new dict
In [20]: for _ in xrange(4):
....: h,j=map(int,raw_input().split())
....: dic.setdefault(h,[]).append(j)
....:
1 10
1 20
2 30
3 5
In [21]: dic
Out[21]: {1: [10, 20], 2: [30], 3: [5]}
辞書のソート:
辞書をソートすることはできませんが、ソートされたkey,value
ペアのリストを取得するか、keys
または単にvalues
使用することができますsorted
:
In [25]: dic={1: [10, 30], 2: [30], 3: [5,50]}
In [26]: sorted(dic.items(),key=lambda x:sum(x[1])) #sort based on sum of lists
Out[26]: [(2, [30]), (1, [10, 30]), (3, [5, 50])]
キーが挿入された順序が保持されるため、 をorderedDict
使用してこの前のリストからを作成できます。collections.OrderedDict
In [27]: from collections import OrderedDict
In [30]: od=OrderedDict(sorted(dic.items(),key=lambda x:sum(x[1])))
In [31]: od
Out[31]: OrderedDict([(2, [30]), (1, [10, 30]), (3, [5, 50])])