分配如何与Python列表切片一起使用? [英] How assignment works with Python list slice?

查看:80
本文介绍了分配如何与Python列表切片一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python文档说切片列表会返回一个新列表.
现在,如果要返回新"列表,我将对分配给切片"存在以下疑问

Python doc says that slicing a list returns a new list.
Now if a "new" list is being returned I've the following doubts related to "Assignment to slices"

a = [1, 2, 3]
a[0:2] = [4, 5]
print a

现在输出为:

[4, 5, 3] 

  1. 正在返回内容的东西如何出现在表达式的左侧?
  2. 是的,我阅读了文档,并说有可能,因为切片列表返回一个新"列表,为什么要修改原始列表?我无法理解其背后的机制.

推荐答案

您正在混淆使用非常相似的语法的两个不同的操作:

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

a的切片替换为b的内容.

This replaces the slice of a with the contents of b.

尽管语法相似(我想是通过设计实现的!),但这是两个不同的操作.

Although the syntax is similar (I imagine by design!), these are two different operations.

这篇关于分配如何与Python列表切片一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆