Python如果一个数字在列表中,但不是列表中的最后一个数字,该如何查找?

Python如果一个数字在列表中,但不是列表中的最后一个数字,该如何查找?,python,Python,我有一个数字列表,想知道列表中是否有一个数字,但不是列表中的最后一个数字。也许是这样的 for i in all_guesses: if guess == i: if guess != all_guesses[-1]: #Code here 唯一的问题是,如果列表中有重复的元素,而其中一个元素位于列表的末尾,那么它将不起作用。asindex返回首次出现的索引 l1 = [1,2,3] l2 = [1,2,3,4] n = 3 p

我有一个数字列表,想知道列表中是否有一个数字,但不是列表中的最后一个数字。也许是这样的

for i in all_guesses:
        if guess == i:
            if guess != all_guesses[-1]:
            #Code here
唯一的问题是,如果列表中有重复的元素,而其中一个元素位于列表的末尾,那么它将不起作用。as
index
返回首次出现的索引

l1 = [1,2,3]
l2 = [1,2,3,4]
n = 3

print( (n in l1 and n != l1[-1]) )
print( (n in l2 and n != l2[-1]) )
唯一的问题是,如果列表中有重复的元素,而其中一个元素位于列表的末尾,那么它将不起作用。as
index
返回首次出现的索引

l1 = [1,2,3]
l2 = [1,2,3,4]
n = 3

print( (n in l1 and n != l1[-1]) )
print( (n in l2 and n != l2[-1]) )
导致

False
True
导致

False
True

使用中的
测试表单成员资格和切片以排除最后一个数字:

print(guess in my_list[:-1])
编辑: OP不清楚如果列表中存在重复元素,特别是如果最后一个元素在列表中的其他位置重复/存在,那么期望的输出是什么。在这种情况下,您需要检查它是否不等于最后一个元素

print(guess in my_list[:-1] and guess != my_list[-1])

使用
中的
测试表单成员资格和切片以排除最后一个数字:

print(guess in my_list[:-1])
编辑: OP不清楚如果列表中存在重复元素,特别是如果最后一个元素在列表中的其他位置重复/存在,那么期望的输出是什么。在这种情况下,您需要检查它是否不等于最后一个元素

print(guess in my_list[:-1] and guess != my_list[-1])

将列表中的最后一个元素切掉

>>> my_list = [3, 1, 4, 6]
>>> without_last = my_list[:-1]
>>> without_last
[3, 1, 4]
>>> 
>>> guess = 6
>>> guess in my_list
True
>>> guess in without_last
False

如果你必须经常这样做(如果你的列表包含了不止几个元素),考虑用

构造一个用于常数时间成员资格测试的集合。
without_last = set(my_list[:-1])

将列表中的最后一个元素切掉

>>> my_list = [3, 1, 4, 6]
>>> without_last = my_list[:-1]
>>> without_last
[3, 1, 4]
>>> 
>>> guess = 6
>>> guess in my_list
True
>>> guess in without_last
False

如果你必须经常这样做(如果你的列表包含了不止几个元素),考虑用

构造一个用于常数时间成员资格测试的集合。
without_last = set(my_list[:-1])

[:-1]
对列表进行切片,并用
中的
检查数字

listOfValues = [1, 2, 3, 4]
number = 1
if number in listOfValues[:-1]:
    print(number)

[:-1]
对列表进行切片,并用
中的
检查数字

listOfValues = [1, 2, 3, 4]
number = 1
if number in listOfValues[:-1]:
    print(number)

可能是:
[x代表x,如果x!=所有猜测[-1]]
可能是:
[x代表x,如果x!=所有猜测[-1]]