[英]Python How do I find if an number is in a list but is not last number of the list?
I have a list of numbers and want to know if a number is in the list but is not the last number in the list. 我有一个数字列表,想知道列表中是否有数字,但不是列表中的最后一个数字。 Maybe something like this?
也许是这样的吗?
for i in all_guesses:
if guess == i:
if guess != all_guesses[-1]:
#Code here
use in
to test form membership and slicing to exclude the last number: 使用
in
测试形式的会员和切片,以排除最后的数字:
print(guess in my_list[:-1])
EDIT: OP is not clear as to what is desired output incase there are repeating elements in the list, in particular if the last elements is repeated/present elsewhere in the list. 编辑:如果列表中有重复元素,OP尚不清楚所需的输出,特别是如果最后一个元素在列表中的其他地方重复/存在时,则尤其如此。 In this case you need to check that it's not equal to last element.
在这种情况下,您需要检查它是否不等于最后一个元素。
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"
The only problem is, it won't work if you have duplicate elements in the list and one is at the end of the list. 唯一的问题是,如果列表中有重复的元素,而列表的末尾有一个元素,则它将不起作用。 as
index
returns the index of first occurance. 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]) )
results in 结果是
False
True
Slice the last element off your list. 从列表中切出最后一个元素。
>>> 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
If you have to do this queck often (and if your list contains more than a few elements) consider constructing a set for the constant-time membership test with 如果您必须经常执行此操作(并且您的列表包含多个元素),请考虑使用以下方法构造一个常数成员资格测试的集合
without_last = set(my_list[:-1])
Slice the list with [:-1]
and check the number with in
使用
[:-1]
分割列表,并使用in
的数字检查
listOfValues = [1, 2, 3, 4]
number = 1
if number in listOfValues[:-1]:
print(number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.