[英]Python : why results are same when i put int or list or tuple in list?
>>> aa = [10, 20, 30]
>>> aa[1:2] = 100, 200
[10, 100, 200, 30]
>>> aa = [10, 20, 30]
>>> aa[1:2] = [100, 200]
[10, 100, 200, 30]
>>> aa = [10, 20, 30]
>>> aa[1:2] = (100, 200)
[10, 100, 200, 30]
I'm a beginner to Python.我是 Python 的初学者。 I tried to change
20
into 100, 200
, so I tried 3 ways of inserting these 2 numbers: ints, a list, and a tuple.我尝试将
20
更改为100, 200
,因此我尝试了 3 种插入这两个数字的方法:整数、列表和元组。 Why is the result the same when I insert ints or a list or a tuple in aa[1:2]?为什么在 aa[1:2] 中插入整数或列表或元组时结果相同?
By using aa[1:2]
, you are modifying a list item using slice assignment.通过使用
aa[1:2]
,您正在使用切片分配修改列表项。 Slice assignment replaces the specified item (or items), in this case the second item in aa
, with whatever new item(s) that is specified.切片分配用指定的任何新项目替换指定的项目(或多个项目),在这种情况下是
aa
的第二个项目。 I'll go through each type to clarify what is happening我将通过每种类型来澄清正在发生的事情
Ints - aa[1:2] = 100, 200
: this example is the most clear. Ints -
aa[1:2] = 100, 200
:这个例子是最清楚的。 We are replacing aa[1:2]
with two ints that go into the list in that spot.我们将
aa[1:2]
替换为两个整数,这些整数进入该位置的列表中。
List/Tuple: this example of how slice assignment works -- instead of adding a list to the list, it extends the new list into the old list.列表/元组:这个切片分配如何工作的示例——它不是向列表添加列表,而是将新列表扩展到旧列表中。 The tuple works the same way.
元组的工作方式相同。 To replace the item and add a list or tuple, wrap the list or tuple in another list first:
要替换项目并添加列表或元组,请先将列表或元组包装在另一个列表中:
>>> aa = [10, 20, 30]
>>> aa[1:2] = [[100, 200]]
[10, [100, 200], 30]
>>> aa = [10, 20, 30]
>>> aa[1:2] = [(100, 200)]
[10, (100, 200), 30]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.