私は辞書がいっぱいです。辞書から任意の要素にアクセスするPythonic方法
print "Amongst our dictionary's items are such diverse elements as: %s" % arb(dictionary)
私は1つの任意の項目を覗いてみたいと思います。 ランダムである必要はありません。
私はこれを実装する多くの方法を考えることができますが、それらはすべて無駄に見えます。私はPythonで好みのイディオムがあるのか、それとも欠けているのであれば(さらに良いのか)疑問に思います。
def arb(dictionary):
# Creates an entire list in memory. Could take a while.
return list(dictionary.values())[0]
def arb(dictionary):
# Creates an entire interator. An improvement.
for item in dictionary.itervalues():
return item
def arb(dictionary):
# No iterator, but writes to the dictionary! Twice!
key, value = dictionary.popitem()
dictionary[key] = value
return value
私はパフォーマンスが十分に重大(まだ)この問題は、私は時期尚早の最適化と非難できることではない位置にいるが、私はので、もし、私のPythonのコーディングスタイルを改善しようとしています容易に理解できる変形があり、それを採用するのが良いでしょう。これは、Python 3のように、同様のpython 2に動作しますが、パイソン2に、それはこのようにそれを行うには、より効率的です
return next(iter(dictionary.values()))
:私の意見では、あなたの第二の溶液に似ていますが、もう少し明らか
'dictionary.itervalues()。next()はどうですか?それは少なくともあなたの2番目の 'arb'関数よりも優れています。 – srgerg
@sgerg私はそれを提出しようとしていたが、あなたは先に進む。 :D – jamylak
彼らは通話中に異なるアイテムにする必要がありますか?これらはすべて同じ項目を返します。 –