Python 简明教程
Python - Change List Items
Change List Items
List is a mutable data type in Python. It means, the contents of list can be modified in place, after the object is stored in the memory. You can assign a new value at a given index position in the list
Example
在以下代码中,我们更改了给定列表中索引 2 的值。
In the following code, we change the value at index 2 of the given list.
list3 = [1, 2, 3, 4, 5]
print ("Original list ", list3)
list3[2] = 10
print ("List after changing value at index 2: ", list3)
它将生成以下 output −
It will produce the following output −
Original list [1, 2, 3, 4, 5]
List after changing value at index 2: [1, 2, 10, 4, 5]
Change Consecutive List Items
您可以用另一个子列表替换列表中连续的更多项。
You can replace more consecutive items in a list with another sublist.
Example
在以下代码中,用另一个子列表中的项替换了索引 1 和 2 处的项。
In the following code, items at index 1 and 2 are replaced by items in another sublist.
list1 = ["a", "b", "c", "d"]
print ("Original list: ", list1)
list2 = ['Y', 'Z']
list1[1:3] = list2
print ("List after changing with sublist: ", list1)
它将生成以下 output −
It will produce the following output −
Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'Y', 'Z', 'd']
Change a Range of List Items
如果源子列表的项多于要替换的部分,则会插入源中的额外项。请看以下代码 −
If the source sublist has more items than the slice to be replaced, the extra items in the source will be inserted. Take a look at the following code −
Example
list1 = ["a", "b", "c", "d"]
print ("Original list: ", list1)
list2 = ['X','Y', 'Z']
list1[1:3] = list2
print ("List after changing with sublist: ", list1)
它将生成以下 output −
It will produce the following output −
Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'X', 'Y', 'Z', 'd']
Example
如果要用来替换原始列表的部分的子列表的项较少,则将匹配的项替换,并删除原始列表中的其余项。
If the sublist with which a slice of original list is to be replaced, has lesser items, the items with match will be replaced and rest of the items in original list will be removed.
在以下代码中,我们尝试用“Z”(少于要替换的项)替换“b”和“c”。其结果是 Z 替换 b 并删除 c。
In the following code, we try to replace "b" and "c" with "Z" (one less item than items to be replaced). It results in Z replacing b and c removed.
list1 = ["a", "b", "c", "d"]
print ("Original list: ", list1)
list2 = ['Z']
list1[1:3] = list2
print ("List after changing with sublist: ", list1)
它将生成以下 output −
It will produce the following output −
Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'Z', 'd']