2014-04-09 46 views
2

我有一個包含值和一堆None的列表。例如:python找到不是「無」的列表中的最後一個值的索引

a = ['a', 'b', None, 4, 5, None, 5, 4, None, 7, None, None, None, None] 

我正在尋找的方式最快(字符最短編號)進行查找的索引,在這種情況下7,最後非None值。

9應該是輸出。

+0

說「最快(最短的代碼)」,不清楚你是想要性能最快的方法還是最少的字符數。有時你很幸運,他們是一樣的,但往往不是。 – DSM

回答

7

我認爲這是很難被擊敗的東西很明顯,如:

def get_last(a): 
    for i, e in enumerate(reversed(a)): 
    if e is not None: 
     return len(a) - i - 1 
    return -1 

注意reversed()只需創建一個反向迭代器,它不會複製列表。而且由於列表訪問速度很快,即使是非常大的列表,這也應該足夠好。

內部返回中的減法補償了reversed()導致enumerate()向後移動輸入列表的事實,因此循環內部的索引i從結尾處開始。

+0

我覺得這個'next'版本看起來同樣不錯。 – DSM

+0

@unwind:我做了:-)但答案使用算術而不是簡單的「反轉(list(枚舉))」。 – DSM

+1

@DSM但是這又創建了另一個列表:) – thefourtheye

1

你可以只用一個標誌迭代:

target = 0 
for i, val in enumerate(a): 
    if val is not None: 
     target = i 
6

可以使用enumerate函數來獲得一個迭代這給當前索引和項目。我們通過reverseda。因此,如果j不是None,我們將返回序列長度與當前索引之間的差異。我們將所有內容都作爲生成器表達式來使用,所以我們需要使用next函數來提高它。

print next(len(a) - i for i, j in enumerate(reversed(a), 1) if j is not None) 
# 9 
+0

我寧願使用'len(a) - i - 1'而不是'enumerate(...,1)',因爲我覺得枚舉應該從1開始令人困惑。 – njzk2

+0

爲了說明所有值都是None的情況,我會在'next'中加上',-1' – njzk2

+1

@ njzk2返回'-1'不是一個好的選擇,因爲它是Python中的有效列表索引。 – thefourtheye

1

您可以從後面開始,並檢查它是否不是無。

x = next(x for x in reversed(seq) if x is not None) 

編輯:我意識到你正在尋找索引,而不僅僅是價值。以上代碼僅給出序列中最後一個非無元素的值。

您可以添加一個枚舉器來獲取索引。

next(len(seq) - i for i, j in enumerate(reversed(seq), 1) if j is not None) 
+2

這會給出值,而不是索引。 – DSM

+0

已修復。我的錯。它現在提供了兩條信息。也許有人某天只會想要你的編輯答案的值 – Matt

+0

由fourtheye給出,btw – njzk2

2

像這樣:

max(index for index, item in enumerate(a) if item is not None) 
+0

如果所有的值都是無的 – njzk2

+0

當你傳遞無滿的列表時它應該引發異常。這是Pythonic。 –

+1

如果我不得不坐下來閱讀所有這些內容而不知道實際問題是什麼,這對我來說最爲清晰 –

1

試試這個,

>>> a = ['a', 'b', None, 4, 5, None, 5, 4, None, 7, None, None, None, None] 
>>> last_index=0 
>>> for index, i in enumerate(a): 
    if i is not None: 
     last_index= index 


>>> last_index 
9 
>>> 
+0

@ njzk2請參閱更新。如果列表中存在多次7,則 – fledgling

2

使用reduce

a = ['a', 'b', None, 4, 5, None, 5, 4, None, 7, None, None, None, None] 

reduce(lambda n, i : i if a[i] is not None else n, range(0, len(a)), -1) 
1

唐諾ID這樣的東西添加到答案的電流池:

>>> a = ['a', 'b', None, 4, 5, None, 5, 4, None, 7, None, None, None, None] 
>>> [i for i,v in enumerate(a) if v is not None][-1] 
9 
>>> 
+0

不起作用。 – njzk2

+0

啊是的非常真實,編輯 – Harpal

+0

你應該使用'is not None'來反對'!= None' [pep8](http://legacy.python.org/dev/peps/pep-0008/)編程建議。 「像None這樣的單身人士的比較應該總是用」是「或」不是「,而不是平等運算符。」 – Scott

相關問題