Python中index()的替代品

时间:2017-11-10 18:42:44

标签: python list indexing

因此,对于我的任务,我必须找到一种可以解决打印问题的方法' YES'如果列表包含连续顺序中的元素1,2,3。如果列表由于索引方法而包含元素[3,1,2,3],则它不起作用。我该如何解决这个问题?

n=int(input("Enter the number of elements: "))

A=[]
for i in range(0,n):
    print("Entering element", i)
    LstEl=int(input("Please enter the element: "))
    A.append(LstEl)


print(A)
for i in range(0,len(A)):
    if(1 in A and 2 in A and 3 in A):
        post1 = A.index(1)
        post2 = A.index(2)
        post3 = A.index(3)
        if(post1 < post2 and post2 < post3):
            print("YES")        
            break
        else:
            print('NO')
            break
    else:
        print("NO")
        break

谢谢!

3 个答案:

答案 0 :(得分:1)

找到有效的post1值后,您可以使用

检查序列
if A[post1:post1+3] == [1, 2, 3]:
    print('Yes')
    break

使用index()方法的其他参数来查找元素&#39; 1&#39;的连续出现。

答案 1 :(得分:1)

一个选项就是:

# find the indices of all `1`s
one_idxs = (i for (i, v) in enumerate(values) if v == 1)
for idx in one_idxs:
    if values[i : i + 3] == [1, 2, 3]:
        print('YES')
        break
else:
    print('NO')

更简洁的方法是

if any(values[i : i + 3] == [1, 2, 3] for (i, v) in enumerate(values) if v == 1):
    print('YES')
else:
    print('NO')

答案 2 :(得分:0)

以下代码使用生成器函数从较大的列表中提取子列表。如果您不了解生成器功能背后的机制,那么它可能不适合做作业,但如果您感兴趣,可能需要考虑一下。

# A generator function that returns the n-length sublists of list lst
def slider(lst, n):
    start = 0
    while start + n <= len(lst):
        yield lst[start:start+n]
        start += 1


# A function that will return True if sequence needle exists in
#   haystack, False otherwise
def list_contains(haystack, needle):
    for sub in slider(haystack, 3): # Loop through the sublists...
        if sub == needle:           # ... test for equality ...
            return True
    return False

# Code
big = [2,4,6,8,0,1,2,3,1,5,7]       # Hardcoded here, could be created
                                    #   in a loop like you show

seq = [1,2,3]                       # The sequence you're looking for

print(list_contains(big, seq))

您可以通过以下方式查看生成器函数的输出:

big = [2,4,6,8,0,1,2,3,1,5,7]
for sub in slider(big, 3):
    print(sub)

输出:

[2, 4, 6]
[4, 6, 8]
[6, 8, 0]
[8, 0, 1]
[0, 1, 2]
[1, 2, 3]
[2, 3, 1]
[3, 1, 5]
[1, 5, 7]

或者可能更清楚:

#  [2, 4, 6, 8, 0, 1, 2, 3, 1, 5, 7]
   [2, 4, 6]
      [4, 6, 8]
         [6, 8, 0]
            [8, 0, 1]
               [0, 1, 2]
                  [1, 2, 3]
                     [2, 3, 1]
                        [3, 1, 5]
                           [1, 5, 7]