如何将列表的最后一次出现作为输出?

时间:2016-02-27 16:49:50

标签: python list indexing

有人可以解释如何从列表中几个最相同值的索引输出最右边的索引吗?

我的职能:

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?

6 个答案:

答案 0 :(得分:3)

这个简单的解决方案应该:

pandas

更有效的方法是从结束迭代到开始并在找到密钥时返回索引,在最坏的情况下 - 找不到密钥,我们将迭代整个列表。

查看效率更高的版本:

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),以避免在项目时出现边缘情况涉及不同类型的人参见Andriy的answer

答案 1 :(得分:1)

您可以尝试这样的功能

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"

这将获得与您的密钥匹配的最后一个索引。如果没有,将返回“无”。

答案 2 :(得分:1)

这应该可以解决问题:

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'

答案 3 :(得分:1)

逆序遍历 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

答案 4 :(得分:0)

您可以撤消列表,然后使用.index()

index = xs[len(xs) - list(reversed(xs)).index(key)]

顺便说一下,在您的第二个列表中,TrueFalse是布尔值,而不是字符串。

答案 5 :(得分:0)

像这样从后面迭代:

def last_index(xs,key):
    i= len(xs)-1
    while i >=0:
        if xs[i] == key:
            return i
         i -= 1

这样,如果该键不存在,该函数将返回无值