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

时间:2017-06-19 01:57:35

标签: python

我预期的输出:

>>> [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)

为什么?

1 个答案:

答案 0 :(得分:4)

这是因为在python中切片分配的工作原理。您只能将一个iterable分配给一个切片,而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)