![](/img/trans.png)
[英]Using a python for loop to print numbers from a list which are not in order of their index
[英]What is the way to get the starting and ending index from an input list of unique numbers from 1 to 8 which are not in ascending order
我試圖找出如何找到具有輸入約束的開始和結束索引,該列表應僅包含從 1 到 8 的非重復數字。 如果數字不是像 [1,2,4,5,3,7,6,8] 這樣的升序,起始索引和結束索引應該是 2 和 6。我的代碼如下
x = [int(i) for i in input().split()]
k = len(x)
for i in range(len(x)):
if x[i] != i+1:
print(i)
break
for i in range(k-1,0,-1):
if x[k-1] != i+1:
print(i)
break
k -=1
因此,您試圖從列表的兩端找到符合升序的最早索引。
您可以使用列表理解來檢查每個元素是否符合預期
x = list(map(int, input.split())) # another way to process the input
is_correct = [e == i+1 for i, e in enumerate(x)] # returns a boolean list
start = is_correct.index(False)
end = len(x) - is_correct.reverse().index(False) - 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.