且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查列表是否是列表保持顺序的一部分并查找位置

更新时间:2023-11-25 22:26:40

您可以使用

You could use next to fetch the first matching point:

a = [3, 4, 1, 2, 4, 1, 5]
b = [4, 1, 2]

starting_point = next((a[i] for i in range(len(a)) if b == a[i:i + len(b)]), -1)

print(starting_point)

输出

4

更新

如果同时需要索引和索引处的值,请返回索引而不是值,例如:

If you need both the index and the value at the index, return the index instead of the value, for example:

position = next((i for i in range(len(a)) if b == a[i:i + len(b)]), -1)

print("position", position)
print("starting point", a[position])

输出

position 1
starting point 4

请注意更改,现在是 i ,而不是 a [i]

Note the change, now is i instead of a[i]