6

タプル内の次の項目を頻繁に (常にではありませんが) 見つけなければならないシステムがあります。私は現在これを次のようにやっています:

mytuple = (2,6,4,8,7,9,14,3)
currentelement = 4
def f(mytuple, currentelement):
    return mytuple[mytuple.index(currentelement) + 1]
nextelement = f(mytuple, currentelement)

すべての要素は一意であり、タプルに固執していません。必要に応じて、プログラムの早い段階で別のものにすることができます。

私はこれをたくさん行う必要があるので、これを行うためのより効率的な方法があるかどうか疑問に思っていましたか?

4

2 に答える 2

7

ここで辞書を使用します。辞書は、操作O(1)と比較してルックアップを提供します。list.indexO(N)

そして、これは文字列にも機能します。

>>> lis = (2,6,4,8,7,9,14,3)
>>> dic = dict(zip(lis, lis[1:]))
>>> dic[4]
8
>>> dic[7]
9
>>> dic.get(100, 'not found') #dict.get can handle key errors
'not found'

上記の辞書を作成するメモリ効率の良いバージョン:

>>> from itertools import izip
>>> lis = (2,6,4,8,7,9,14,3)
>>> it1 = iter(lis)
>>> it2 = iter(lis)
>>> next(it2)
2
>>> dict(izip(it1,it2))
{2: 6, 4: 8, 6: 4, 7: 9, 8: 7, 9: 14, 14: 3}
于 2013-06-18T09:25:31.183 に答える
1

辞書を使用してインデックスを作成したい場合があります。

# The list
>>> lis = (2,6,4,8,7,9,14,3)

# build the index
>>> index = dict(zip(lis, range(len(lis))))
>>> index
{2: 0, 3: 7, 4: 2, 6: 1, 7: 4, 8: 3, 9: 5, 14: 6}

# Retrieve position by using the index
>>> index[6]
1
>>> lis[index[6]+1]
4

時間の経過とともにリストが変更された場合は、インデックスを再構築する必要があります。よりメモリ効率の高いソリューションについてizipは、他の回答で提案されているように、「zip̀」の代わりに使用することをお勧めします。

于 2013-06-18T10:05:45.543 に答える