gpt4 book ai didi

python - 为什么切片赋值摆脱了Python中的外部元组

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:04 24 4
gpt4 key购买 nike

我期望的输出:

>>> [1, ("Hello", (2, 3)), 4]

...使用此代码:

rl = [1, 4]
test_sl = ("Hello", (2, 3))
rl[1:1] = test_sl
print(rl)

反而给我带来了:

>>> [1, "Hello", (2, 3), 4] # No tuple around "Hello", (2, 3)

为什么?

最佳答案

这是因为切片分配在 python 中的工作方式。您只能将一个可迭代对象分配给一个切片,而 python 会将迭代可迭代对象的所有项目分配给该切片。例如:

>>> def ten():
... for n in range(10):
... yield(n+1)
...
>>> a = ['hello']
# directly assigning an iterable - function that yields things
>>> a[1:1] = ten()
>>> a
['hello', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# a string can be an iterable - iterates over its characters
>>> a[2:2] = 'hello'
>>> a
['hello', 1, 'h', 'e', 'l', 'l', 'o', 2, 3, 4, 5, 6, 7, 8, 9, 10]
# can't assign something that isn't iterable!
>>> a[1:1] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
# as a tuple is iterable, only the contents will be assigned to the list
>>> a[1:1] = ('hello', 'world')
>>> a
['hello', 'hello', 'world', 1, 'h', 'e', 'l', 'l', 'o', 2, 3, 4, 5, 6, 7, 8, 9, 10]

编辑:解决您的问题的一个简单方法可能是使用 python 列表的 insert 方法(我知道不是切片分配,但可能更接近您想要实现的目标):

rl.insert(1, test_sl)

关于python - 为什么切片赋值摆脱了Python中的外部元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44621267/

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