2016-03-22 14 views
0
>>> x = {'a':2, 'b':3} 
>>> [key for key in x for i in range(x[key])] 
['b', 'b', 'b', 'a', 'a'] 

範囲(x [key])のiがない場合、このコードを書く方が良いですか?それともこれを書く良い方法がありますか?範囲内のPythonの理解

答えて

2

あなたは仕事をするためにitertools moduleを使用することができます。

from itertools import chain, starmap, repeat 

list(chain.from_iterable(starmap(repeat, x.items()))) 

これは、あなたが直接使用することができた、Counter.elements() methodが実装されている方法です。

from collections import Counter 

list(Counter(x).elements()) 

を使用すると、リストに固執する場合少なくともitertools.repeat() functionの静止画を使用し、dict.items()(またはさらにはPython 2のdict.iteritems())を使用して、キーと関連する値のペアを与えます。

from itertools import repeat 

[c for key, count in x.items() for c in repeat(key, count)] 

3つ全ては、同じ出力を生成する:キーの相対的順序はdictionary insertion and deletion orderに依存する

>>> from itertools import chain, starmap, repeat 
>>> from collections import Counter 
>>> x = {'a': 2, 'b': 3} 
>>> list(chain.from_iterable(starmap(repeat, x.items()))) 
['a', 'a', 'b', 'b', 'b'] 
>>> list(Counter(x).elements()) 
['a', 'a', 'b', 'b', 'b'] 
>>> [c for key, count in x.items() for c in repeat(key, count)] 
['a', 'a', 'b', 'b', 'b'] 

+0

は私ではなかったです!しかし、iirc、Python 3の地図は引数でこのインスタンスで使うことができます。私が家に帰るときには確かにチェックします。その間に+1して、無意識のうちに誰かのために調整してください。私は個人的には、目標を達成するための複数の方法を提供する回答が、事実上の「これを行う」答えよりも価値があると思います。 –

3

またはカウンターを使用します。

from collections import Counter 

x = Counter({'a':2, 'b':3}) 
print (list(x.elements())) 
# ['b', 'b', 'b', 'a', 'a'] 
関連する問題