小编Cod*_*sci的帖子

字符串索引 - 为什么S [0] [0]有效且S [1] [1]失败?

假设我创建了一个字符串:

>>> S = "spam"
Run Code Online (Sandbox Code Playgroud)

现在我将其索引如下:

>>> S[0][0][0][0][0]
Run Code Online (Sandbox Code Playgroud)

我输出为:

>>> 's'
Run Code Online (Sandbox Code Playgroud)

但当我将其索引为:

>>> S[1][1][1][1][1]
Run Code Online (Sandbox Code Playgroud)

我输出为:

Traceback (most recent call last):
File "<pyshell#125>", line 1, in <module>
L[1][1][1][1][1]
IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)

为什么输出不是'p'?

为什么它也适用于S [0] [0]或S [0] [0] [0]或S [0] [0] [0] [0]而不适用于S [1] [1]或S [1] [1] [1]或S [1] [1] [1] [1]?

python python-2.7 python-3.x

5
推荐指数
2
解决办法
1901
查看次数

python3中的扩展序列解包

我创建一个列表:

>>> seq = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

现在我分配变量如下:

>>> a, b, c, d, *e = seq
>>> print(a, b, c, d, e)
Run Code Online (Sandbox Code Playgroud)

我输出为:

>>> 1 2 3 4 []
Run Code Online (Sandbox Code Playgroud)

现在我改变我将变量赋值为的顺序:

>>> a, b, *e, c, d = seq
>>> print(a, b, c, d, e)
Run Code Online (Sandbox Code Playgroud)

我输出为:

>>> 1, 2, 3, 4, []
Run Code Online (Sandbox Code Playgroud)

所以我的问题是为什么*上面的变量总是被分配一个空列表而不管它出现在哪里?

python python-3.x

4
推荐指数
2
解决办法
601
查看次数

标签 统计

python ×2

python-3.x ×2

python-2.7 ×1