如何检查一个元素在列表中是否在另一个元素之前?
例如:
如何检查列表中的5是否在12之前:
li = [1,2,3,7,4,5,10,8,9,12,11]
有没有内置的Python函数可以让我做到这一点?
如何检查一个元素在列表中是否在另一个元素之前?
例如:
如何检查列表中的5是否在12之前:
li = [1,2,3,7,4,5,10,8,9,12,11]
给你:
>>> 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.
>>>
if li.index(5) < li.index(12):
print "came before"
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
内置的索引函数吗? - user2555451let 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);
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
li.index(5) < li.index(12)
,请翻译成中文。 - Joran Beasley[1,12,3,4,5,6,12,1,2,3,5]
这个怎么处理?这里的问题是在 12 之前是否有 5。 - oleg