如何使用python返回列表中1(int)之后的值True(bool)索引

如何使用python返回列表中1(int)之后的值True(bool)索引,python,indexing,Python,Indexing,我需要在Python中执行一个函数来接收两个参数“item”对象和“list”列表,并返回列表中项目出现位置的索引。 如果列表中没有出现项,则函数返回None 如果列表在布尔值为True之前包含整数1,则函数不起作用(测试2) 以下测试示例: def indice(item, lis): ''' (object,list) -> int ou None Receives an 'item' object and a 'list' list and returns t

我需要在Python中执行一个函数来接收两个参数“item”对象和“list”列表,并返回列表中项目出现位置的索引。 如果列表中没有出现项,则函数返回None

如果列表在布尔值为True之前包含整数1,则函数不起作用(测试2)

以下测试示例:

def indice(item, lis):
    '''
    (object,list) -> int ou None
    Receives an 'item' object and a 'list' list and returns the
    index of the position in which item occurs in the list.
    If item does not occur in the list, the function returns None
    '''
    for i in lista:
        if i == item:
            return (lista.index(item))
    return None

    
lista=[1,“你好”,3.14,7,对]

# test 1
if indice("hi",lista) == 1:
    print("Passed the first test! :-)")
else:
    print("Not passed the first test! :-(")

# test 2
if indice(True,lista) == 4:
    print("Passed the second test! :-)")
else:
    print("Not passed the second test! :-(")

# test 3
if indice(False,lista) == None:
    print("Passed the third test! :-)")
else:
    print("Not passed the third test! :-(")
输出:

Passed the first test! :-)
Nao passed the second test! :-(
Passed the third test! :-)

感谢您的帮助。

出现此问题是因为在python中
1
相当于
True
0
相当于
False
。因此,在您的代码中,当在索引0处的第一个迭代ie元素中,它检查
1==True
,这将导致
True
语句,然后继续返回部分,从第一个元素ie
index 0
搜索索引,在索引0处,它发现该项与条件匹配,因此
返回0

对代码进行少量修改

def indice(item, lis):
    '''
    (object,list) -> int ou None
    Receives an 'item' object and a 'list' list and returns the
    index of the position in which item occurs in the list.
    If item does not occur in the list, the function returns None
    '''

    for i,v in enumerate(lis):
 
        if v == item and type(v) == type(item):
            return i
    return None

lista = [1,"hi", 3.14, 7, True]
x = indice(True, lista)

print(x) # output 4
使用
enumerate
遍历列表,并将索引和值放在一起,这样就不需要使用
list.index
在本例中会导致错误索引的值

您需要不断检查列表中的项目类型和您要查找的项目
由于
1==True
True
但两者的类型不同,一种是
int
类型,另一种是
bool
类型。因此,比较对象的
类型将解决您的问题。

顺便说一句:
index()
不是一个好主意,因为它为第一项提供索引。如果您将拥有相同的项目两次(或更多),并且您需要第二个项目(或下一个项目)的索引,那么它将为您提供第一个项目的索引。谢谢@sahasrara62。我尝试使用enumerate,但不是作为索引。@EduardoRocha欢迎使用,它只是您代码之上的一个修改代码,我将尝试使用。关键是要理解这个概念以及为什么代码会这样。希望你明白这一点