Check if List is part of List keeping order and find postion

放肆的年华 提交于 2021-01-28 05:11:58

问题


I need to seek the "matchingpoint" of two list where List "a" is bigger than List "b". So far I've found this earlier post: Check if a list is part of another list while preserving the list sequence

That helps a lot. But I need to now, where the lists fit.

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

"b" fits in "a" but instead of a TRUE value I would like to have a[1] as first matchingpoint


回答1:


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)

Output

4

UPDATE

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])

Output

position 1
starting point 4

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



来源:https://stackoverflow.com/questions/64907723/check-if-list-is-part-of-list-keeping-order-and-find-postion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!