更新时间: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]