直接在if else语句中索引时出现python索引错误

dphi5xsq  于 2023-05-05  发布在  Python
关注(0)|答案(1)|浏览(194)

当我试图解决ctf挑战,我得到了索引错误,但我不知道是什么问题,我的代码
如果我运行这段代码

import string

arr1 = ['21', 'cf', '28', 'd6', '77', 'a3', '27', 'd2', '77', '2f', '85', '04', 'db', '35', '4d', '6f', 'a5', 'c3', 'd8', '64', '85', 'fe', '64', '6b', 'c0', '14', '5c', '13', '5f', '49', '0f', 'df', 'd8']
arr2 = ['73', '8a', '6c', '84', '32', 'e7', '75', '97', '33', '7d', 'c0', '40', '89', '70', '09', '3d', 'e0', '87', '8a', '21', 'c1', 'ac', '21', '2f', '92', '51', '18', '41', '1a', '0d', '5d', '9a', '9c']

txt = ''
i = 0
while (i < 33):
    for a in string.printable:
        if ord(a) ^ int(arr1[i], 16) ^ int(arr2[i], 16) == 0:
            txt += a
            i += 1
print(txt)

我得到了这个错误

Traceback (most recent call last):
  File "d:\tempCodeRunnerFile.python", line 9, in <module>
    if ord(a) ^ int(arr1[i], 16) ^ int(arr2[i], 16) == 0:
                    ~~~~^^^
IndexError: list index out of range

但如果我把arr1[i]或arr2[i]存储到另一个变量中

import string

arr1 = ['21', 'cf', '28', 'd6', '77', 'a3', '27', 'd2', '77', '2f', '85', '04', 'db', '35', '4d', '6f', 'a5', 'c3', 'd8', '64', '85', 'fe', '64', '6b', 'c0', '14', '5c', '13', '5f', '49', '0f', 'df', 'd8']
arr2 = ['73', '8a', '6c', '84', '32', 'e7', '75', '97', '33', '7d', 'c0', '40', '89', '70', '09', '3d', 'e0', '87', '8a', '21', 'c1', 'ac', '21', '2f', '92', '51', '18', '41', '1a', '0d', '5d', '9a', '9c']

txt = ''
i = 0
while (i < 33):
    x = arr1[i]
    y = arr2[i]
    for a in string.printable:
        if ord(a) ^ int(x, 16) ^ int(y, 16) == 0:
            txt += a
            i += 1
print(txt)

没有错误。怎么可能?

xtfmy6hx

xtfmy6hx1#

在第一示例中:

for a in string.printable:
    if ord(a) ^ int(arr1[i], 16) ^ int(arr2[i], 16) == 0:
        txt += a
        i += 1

i在for循环中递增时,它的新值将在下一次循环迭代中使用。
但在第二个例子中:

x = arr1[i]
y = arr2[i]
for a in string.printable:
    if ord(a) ^ int(x, 16) ^ int(y, 16) == 0:
        txt += a
        i += 1

x = arr1[i]被分配 * 仅一次 *,并且i的任何进一步增量不会影响x
看起来你期望x = arr1[i]是某种持续的永久公式,所以改变i * 会影响x。但事实并非如此。

相关问题