[英]finding the last occurrence of an item in a list python
我希望在序列's'中找到項'x'的最后一次出現,或者如果沒有,則返回None,並且第一項的位置等於0
這就是我目前擁有的:
def PositionLast (x,s):
count = len(s)+1
for i in s:
count -= 1
if i == x:
return count
for i in s:
if i != x:
return None
當我嘗試:
>>>PositionLast (5, [2,5,2,3,5])
>>> 4
這是正確的答案。 但是,當我將'x'更改為2而不是5時,我得到:
>>>PositionLast(2, [2,5,2,3,5])
>>> 5
答案應該是2.我很困惑這是如何發生的,如果有人能解釋我需要糾正的事情,我將不勝感激。 我還想用最基本的代碼來完成這個。
謝謝。
你的邏輯是不正確的,因為你返回計數如果i==x
並且你在函數的尾隨處有一個額外的循環。
而是循環遍歷列表的枚舉的反向形式並返回第一次出現的索引:
def PositionLast (x,s):
return next(i for i,j in list(enumerate(s))[::-1] if j == x)
演示:
print PositionLast (2, [2,5,2,3,5,3])
2
print PositionLast (3, [2,5,2,3,5,3])
5
print PositionLast (5, [2,5,2,3,5,3])
4
你的代碼是錯誤的,它從頭開始檢查列表並在第一個匹配時停止,你想要的是以相反的順序檢查列表。
def PositionLast (x,s):
count = len(s)
for i in s[::-1]:
count -= 1
if i == x:
return count
return None
你的第一行只是因為巧合才給你正確答案:
- 檢查第一項時,計數等於5。
- 檢查第二項時計數等於4,匹配,然后返回4。
- 巧合的是,這是你最后一項的索引。
以相反的順序迭代列表,然后檢查x。 這可能是一種有效的方式,作為逆轉列表,然后從頭開始查找索引是資源密集型的。
def PositionLast (x,s):
for i in range(len(s)-1,0,-1):
if s[i] == x:
return i
return None
def positionLast(x, L):
answer = None
for i,e in enumerate(L):
if e==x: answer = i
return answer
def positionLast(x, L):
try: return max(i for i,e in enumerate(L) if e==x)
except: return None
感謝大家的回復和幫助! 不幸的是,沒有人得到我想要的答案,但無論我最終自己完成了什么,但非常感謝你們!
這是最終的代碼:
def PositionLast(x,s):
count = -1
position = None
for i in s:
count += 1
if i == x:
position = count
return position
這將返回所有測試的正確答案。
謝謝,艾美爾。
def lastposition(array,x):
flag = 0
for i in range(len(array)):
if array[i] == int(x):
x = i
flag = 1
else:
pass
if flag == 0:
print 'None'
else:
print x
array = [2,5,2,3,5]
x = 2
lastposition(array,x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.