为什么使用 [i:i+1] 而不是 [i]?

Mxn*_*gls 0 python

为什么我们不能在这里使用[i]代替[i:i+1]?(第 10 行)。仅供参考:此代码是此处描述的问题的解决方案的一部分:https : //www.codewars.com/kata/57814d79a56c88e3e0000786/train/python 但它更像是一个普遍的问题!我只[i]在我的类似解决方案中使用过,但它给我带来了索引错误。

def decrypt(text, n):
    if text in ("", None):
        return text

    ndx = len(text) // 2

    for i in range(n):
        a = text[:ndx]
        b = text[ndx:]
        text = "".join(b[i:i+1] + a[i:i+1] for i in range(ndx + 1))
    return text



def encrypt(text, n):
    for i in range(n):
        text = text[1::2] + text[::2]
    return text
Run Code Online (Sandbox Code Playgroud)

Luk*_*ler 10

Usinglist[i]将生成一个元素, usinglist[i:i+1]将生成一个包含一个元素的列表。由于join需要一个列表作为参数,使用前者会出错,而使用后者按预期工作

lst = [1,2,3]

lst[1]
2

lst[1:2]
[2]
Run Code Online (Sandbox Code Playgroud)