2011-10-07 40 views
0

看來愚蠢寫:試驗列表成員和在Python的同時獲得指數

L = [] 

if x in L: 
    L[x] = something 
else: 
    L[x] = something_else 

這難道不執行兩次查找關於x?我試過使用index(),但是當這個值沒有找到時,這會產生一個錯誤。

理想我想說這樣的:

if x is in L, save that index and: 
    ... 

我能夠理解,這可能是一個初學者蟒蛇成語,但它似乎相當非搜索能力。謝謝。

+2

您正在使用字典,它們沒有索引或像列表一樣排序。 – birryree

+0

標題說明名單,我認爲字典是一個錯字 –

+0

你的問題有一些字典的意義。現在它只是毫無意義... – JBernardo

回答

2

另一種選擇是嘗試/除外:

d = {} 
try: 
    d[x] = something_else 
except KeyError: 
    d[x] = something 

結果與您的代碼相同。

編輯:好吧,快速移動的目標。列表的相同用法,不同的異常(IndexError)。

+2

'd [x] = something_else'永遠不會產生KeyError。它只會分配/覆蓋該值。檢索該值時會生成KeyError,但不會對其進行設置。 – warvariuc

+0

我同意@warvariuc。沒有KeyError異常將在那裏提出一個字典類型。 – DevPlayer

+0

另外something_else應該在'except'之下。如果這個例子是一個列表,其中'L = []'你會在'except'子句中再次得到一個異常,因爲'L [x]'仍然會引發一個異常。 – DevPlayer

2

你的意思是你想setdefault(key[, default])

a = {} 
a['foo'] # KeyError 
a.setdefault('foo', 'bar') # key not exist, set a['foo'] = 'bar' 
a.setdefault('foo', 'x') # key exist, return 'bar' 
1

如果你有列表可以使用index,捕捉ValueError如果拋出:

yourList = [] 
try: 
    i = yourList.index(x) 
except ValueError: 
    i = None 

然後你就可以測試值的i:

if i is not None: 
    # Do things if the item was found. 
0

我認爲你的問題讓很多人感到困惑,因爲你在dict和list之間混合了你的語法。 如果:

L = [] # L is synonym for list and [] (braces) used to create list() 

在這裏,你正在尋找一個列表中的值,的關鍵也不在一個字典值:

if x in L: 

然後使用X看似意一個鍵,但在列表中它是一個int()索引,並且if x in L:不測試以查看索引是否在L中,但是如果值在L中:

L[x]=value 

所以,如果你打算看一個值是L列表做:

L = []    # that's a list and empty; and x will NEVER be in an empty list. 
if x in L:   # that looks for value in list; not index in list 
         # to test for an index in a list do if len(L)>=x 
    idx = L.index(x) 
    L[idx] = something # that makes L[index]=value not L[key]=value 
else: 
    # x is not in L so you either append it or append something_else 
    L.append(x) 

如果你使用: L[x] = somethingif x in L:在一起,然後它將使意義有一個列表,只有這些值:L=[ 0, 1, 2, 3, 4, ...] OR L=[ 1.0, 2.0, 3.0, ...]

但是我提供這樣的:

L = [] 
L.extend(my_iterable) 
coder0 = 'farr' 
coder1 = 'Mark Byers' 
if coder0 not in L: 
    L.append(coder1) 

奇怪的邏輯

相關問題