即使它特别指出索引0,for循环如何检查每个索引号?

时间:2018-12-31 15:14:33

标签: python python-3.x

这是代码中断问题的解决方案,我没有找到解决方案。

  

间谍游戏:编写一个函数,该函数接受一个整数列表,如果顺序包含007,则返回True

def spy_game(nums):

   code = [0,0,7,'x']

   for num in nums:
       if num == code[0]:
           code.pop(0)   # code.remove(num) also works

   return len(code) == 1

这个for循环如何特别检查索引0,但如何检查每个索引号?

3 个答案:

答案 0 :(得分:2)

由于您执行了code.pop(0),因此将从列表code中删除索引0处的元素。当您使用[0, 0, 7]调用函数时,将进行以下循环迭代:

nums = [0, 0, 7]
code = [0, 0, 7, 'x']

# First iteration
num = 0 (first element of nums)
num == code[0] is true
code[0] is removed
code = [0, 7, 'x']

# Second iteration
num = 0 (second element of nums)
num == code[0] is true
code[0] is removed
code = [7, 'x']

# Third iteration
num = 7 (third element of nums)
num == code[0] is true
code[0] is removed
code = ['x']

# End of the loop
All elements of nums have been iterated, so the loop is over

code = ['x']
len(code) == 1 is true
True is returned

答案 1 :(得分:0)

def spy_game(nums):
    mylist =  list(enumerate(nums))
    myupdatedlist = []

    for a,b in mylist:
        if b ==0 or b ==7:
            myupdatedlist.append(tuple((a,b)))
    if myupdatedlist[0][1] == 7:
        return False
    else:
        return True
    pass

答案 2 :(得分:-1)

我是这样做的:

def myfunc(a):
    for c, b in enumerate(a):
        if b == 0 and a[c+1] == 0 and a[c+2] == 7:
            return True
    return False

myfunc([0, 2, 7])

输出

False