gpt4 book ai didi

python - 当我知道我不应该能够时向元组添加元素

转载 作者:太空狗 更新时间:2023-10-30 00:24:36 25 4
gpt4 key购买 nike

Dive Into Python是众多消息来源之一:

You can't add elements to a tuple.

但看起来好像我被允许那样做。我的代码:

from string import find

def subStringMatchExact(target, key):
t = (99,)
location = find(target, key)
while location != -1
t += (location,) # Why is this allowed?
location = find(target, key, location + 1)
return t

print subStringMatchExact("atgacatgcacaagtatgcat", "tg")

输出:

(99, 1, 6, 16)

这让我相信我在初始化 t 时实际上并没有创建元组。谁能帮我理解一下?

最佳答案

您正在将 2 个元组连接成一个新元组。您没有修改原件。

> a = (1,)
> b = a
> b == a
True
> a += (2,)
> b == a
False

关于python - 当我知道我不应该能够时向元组添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5756768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com