分配如何与列表切片一起使用? [英] How does assignment work with list slices?
本文介绍了分配如何与列表切片一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python 文档说切片列表会返回一个新列表.
现在,如果一个新"正在返回列表 我有以下与分配给切片"相关的问题
Python docs says that slicing a list returns a new list.
Now if a "new" list is being returned I've the following questions related to "Assignment to slices"
a = [1, 2, 3]
a[0:2] = [4, 5]
print a
现在输出将是:
[4, 5, 3]
- 返回的东西怎么会出现在表达式的左侧?
- 是的,我阅读了文档,它说这是可能的,因为切片列表会返回一个新"list,为什么原来的list被修改了?我无法理解其背后的机制.
推荐答案
你混淆了两个使用非常相似语法的不同操作:
You are confusing two distinct operation that use very similar syntax:
1) 切片:
b = a[0:2]
这会复制a
的切片并将其分配给b
.
This makes a copy of the slice of a
and assigns it to b
.
2) 切片分配:
a[0:2] = b
这用b
的内容替换a
的切片.
尽管语法相似(我是故意设计的!),但这是两种不同的操作.
Although the syntax is similar (I imagine by design!), these are two different operations.
这篇关于分配如何与列表切片一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文