如何获取最后一次出现的列表作为输出?
任何人都可以请解释如何从列表中的几个最相同的值索引输出最右边的索引?如何获取最后一次出现的列表作为输出?
我的功能:
def last_index(xs,key):
i = 0
for i in range(len(xs)):
if xs[i] == key:
if i != len(xs):
return i
else:
return 'None'
例如,
xs = [3,4,5,6,4,4,5]
key = 4
最右边的指数输出应该是一个单一的5,但我得到了所有三个个个它们是指数1,4,5。 感谢您的帮助,对不起,我是全新的。
如果什么输入像字符串:
xs=[True,True,True,False]
key = True
我相信,输出为2?
这种简单的解决方案应该做到:
def last_index(xs, key):
index = None
for i in xrange(len(xs)):
if xs[i] == key:
index = i # override index, result in the rightmost index of key
return index # returns None if key is not on the list
更有效的方式来做到这一点是从最终迭代开始并返回索引时关键是找到,在最坏的情况下 - 关键是没有找到,我们将遍历整个列表。
检查出更有效的版本:
def last_index(xs, key):
index = None
for i in xrange(len(xs)-1, 0, -1): # iterate from last item to first
if xs[i] == key:
index = i
break # found the rightmost index, exit the loop
return index
通知你应该更喜欢使用xrange
超过range
(除非python 3
其中range
等于xrange
),也避免了在项目涉及不同类型看到舍甫琴科的边缘情况answer。
可以撤消列表,然后使用.index()
:
index = xs[len(xs) - list(reversed(xs)).index(key)]
顺便说一句,在你的第二个列表,True
和False
是布尔值,而不是字符串。
你可以尝试这样的函数
def last_index(xs,key):
index = -1
for i in range(len(xs)):
if xs[i] == key:
index=i
if index!=-1:
return index
else:
return "none"
这将让你的密钥相匹配的最后一个索引。如果没有将返回“无”。
这应该做的伎俩:
def last_index(xs,key):
index = -1
for i in range(len(xs)):
if xs[i] != key:
continue
else:
index = i
return index if index != -1 else 'None'
特拉弗斯XS在相反的顺序并返回第一个匹配值,与reversed功能:
def last_index(xs,key):
for i in reversed(range(len(xs))):
if xs[i] == key:
return i
xs = [3,4,5,6,4,4,5]
key = 4
print last_index(xs, key) # output: 5
xs=[True,True,True,False]
key = True
print last_index(xs, key) # output: 2
print last_index(xs, 2) # output: None
注#1
您可以使用xrange
而不是range
它会给你更好的性能,并且不会因为python3而被弃用,请参阅Should you always favor xrange() over range()?了解更多信息。
您的比较可以通过更换
if xs[i] == key
到
if xs[i] == key and type(a) == type(b)
注#2
为了避免错误,当你1 == True
将返回True
但是你想你的索引来提高指数1不存在,比较两种情况下的结果,如果xs和key有条件的话下面
xs=[True,True,True,False]
key = 1
值有关行为的详细信息,请参阅Strict comparison。
只需要注意,如果他使用python 3,那么他必须使用范围(xrange在python 3中不再存在)。 –
@哈德良感谢,指出那一刻。 –
迭代从背后是这样的:
def last_index(xs,key):
i= len(xs)-1
while i >=0:
if xs[i] == key:
return i
i -= 1
这样,如果该键不存在,该函数将返回none值
我认为问题是关于列表 – AlokThakur
计数键发生HTTP的重复://stackoverflow.com/questions/6890170/how-to-find-the-last-occurrence-of-an-item-in-a-python-list – SPKoder
@AlokThakur是的。我太快读了这个问题。我的错。我收回了它。 – idjaw