简体   繁体   English

Python:为什么当我将 int 或 list 或 tuple 放入列表时结果相同?

[英]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.

相关问题 为什么当我在 python 上放置双循环时我的列表没有重复 - Why is my list not reiterating when I put a double loop on python Python:为什么追加到列表会产生相同的值 - Python: why appending to a list results in same values 为什么 Python 将列表匹配为元组? - Why Python matches a list as a tuple? 在 Python 中,为什么元组可以散列而不是列表? - In Python, why is a tuple hashable but not a list? 在Python3中将值添加到list和int的元组 - Add value to a tuple of list and int in Python3 当 Python 语法似乎支持它时,为什么我不能用元组对列表进行切片? - Why can't I slice a list with a tuple, when it seems to be supported by the Python grammar? 为什么我不能在Python中使用'+'运算符将列表添加到列表中? - Why can't I add a tuple to a list with the '+' operator in Python? 如何将python中的list转成tuple,list的所有元素都应该是int? - how to convert list into tuple in python , all elements of list should be in int? 为什么相同的代码返回列表和元组 pandas? - Why same code return list and tuple pandas? 为什么当我随机 select 一个要放入列表的数字时,它总是选择相同的起始数字? - Why when i randomly select a number to be put into a list it always picks the same starting number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM