繁体   English   中英

Python如何查找列表中是否有数字,而不是列表的最后一个数字?

[英]Python How do I find if an number is in a list but is not last number of the list?

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

for i in all_guesses:
        if guess == i:
            if guess != all_guesses[-1]:
            #Code here

使用in测试形式的会员和切片,以排除最后的数字:

print(guess in my_list[:-1])

编辑:如果列表中有重复元素,OP尚不清楚所需的输出,特别是如果最后一个元素在列表中的其他地方重复/存在时,则尤其如此。 在这种情况下,您需要检查它是否不等于最后一个元素。

print(guess in my_list[:-1] and guess != my_list[-1])
If guess in all_guesses and all_guesses.index(guess)! = len(all_guesses):
    print "Present but not last" 

唯一的问题是,如果列表中有重复的元素,而列表的末尾有一个元素,则它将不起作用。 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

从列表中切出最后一个元素。

>>> 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]分割列表,并使用in的数字检查

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM