如何检查列表中的一个数字是否在另一个数字之前。

3

如何检查一个元素在列表中是否在另一个元素之前?

例如:

如何检查列表中的5是否在12之前:

li = [1,2,3,7,4,5,10,8,9,12,11]

有没有内置的Python函数可以让我做到这一点?

2
这段程序相关的内容是:li.index(5) < li.index(12),请翻译成中文。 - Joran Beasley
2
[1,12,3,4,5,6,12,1,2,3,5] 这个怎么处理?这里的问题是在 12 之前是否有 5。 - oleg
4个回答

6

给你:

>>> li = [1,2,3,7,4,5,10,8,9,12,11]
>>> li.index(5) > li.index(12)    # 5 comes after 12
False
>>> li.index(5) < li.index(12)    # 5 comes before 12
True
>>>
>>> help(list.index)
Help on method_descriptor:

index(...)
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

>>>

3
if li.index(5) < li.index(12):
   print "came before"

0
你可以使用列表的内置函数index
>>> l = [1,2,3,7,3,5,21,8,44,16,12]
>>> l.index(5) > l.index(12)
False
>>> l.index(5) < l.index(12)
True
>>>

index 返回第一个数字出现的索引位置。下面是 index 的使用示例:

>>> t = (0,1,2,3,4,0,1,2)
>>> t.index(3)
3
>>> t.index(0)
0

请注意这里有两个0

你是指list内置的索引函数吗? - user2555451
@iCodez 你说得对。我总是使用字符串对象,所以有时会忘记 :P - Games Brainiac

-3
我不懂Python,但通常编程语言中的数组和列表使用基于零的索引来标识每个元素。您通常可以通过使用格式li[index] = element访问每个元素的索引。例如:
let li = [1,2,3,7,4,5,10,8,9,12,11]

li[0] = 1;
li[1] = 2;
li[2] = 3;
li[3] = 7;
li[4] = 4;

等等。许多系统也会有一个IndexOf()方法,它允许您使用类似li.IndexOf(element)的格式确定元素的索引。此功能可以在您的示例中使用,例如:

Boolean Is_5_B4_12 = li.IndexOf(5) < li.IndexOf(12);

如果Python没有这样的功能,你可以通过使用循环和一个递增器来轻松地创建一个。类似于下面的代码会起作用:
Function IndexOf(integer element)
    integer index = 0;
    Do While index < len(li) //len() is a function that specifies the number of elements in the list
        if li[index] == element then return index;
        index = index + 1;
    Loop
End Function

希望这个回答解决了你的问题!祝好 - yisrael lax


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接