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

标签 python python-3.x

这是一个代码破坏问题的解决方案,但我没有得到解决方案。

SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order

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?

最佳答案

由于执行了 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

关于python - 这个 for 循环如何检查每个索引号,即使它特别指出索引 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53988901/

相关文章:

python - 当Python中有25个单词时,如何读取文件并插入新行

python - 将一个列表中声明的价格分配给其他列表中的项目并计算总价 - Python

python - 从命令行跳过 pytest 中的导入模块

python-3.x - python3中的“和”运算符

python - 交互式地改变 Bokeh 图中的字形

python-3.x - 找不到满足 python 3 conda 的版本

python 3 不确定行为

python - 使用 Python 图像库进行抗锯齿时,使用透明消除边缘处的细边框

python - pandas如何计算仅给定月份和日期的增量

python-3.x - 如何将不同列的 value_count() 值打印在一起?