在列表中用一个项替换两个项

huangapple go评论65阅读模式
英文:

Replacing two items with one item in a list

问题

如何在Python中用单个元素替换列表中的两个元素?

例如:

list_a = [1, 2, 3, 4, 5, 6, 7]

如果我想用9替换2和3,我只知道它们的索引(我不知道值)

list_a = [1, 9, 4, 5, 6, 7]

英文:

How to replace two elements in a list with single element in Python?

For example:

list_a = [1, 2, 3, 4, 5, 6, 7]

if I wanted to replace 2 and 3 with let's say 9 and I only know the indices, (I don't know the values)

list_a = [1, 9, 4, 5, 6, 7]

答案1

得分: 9

在Python中,你可以使用切片并将值分配给列表:

list_a = [1, 2, 3, 4, 5, 6, 7]

list_a[1:3] = [9]   # list_a[1:3] 表示元素 [2, 3]

print(list_a)

输出结果:[1, 9, 4, 5, 6, 7]

请注意,在Python中索引从 0 开始,因此你的切片是 1:3(索引从1到3,不包括3),更多细节请参考Python中切片的工作原理

# 索引:   0  1  2  3  4  5  6
list_a  =  [1, 2, 3, 4, 5, 6, 7]
# 切片:        x  x 
英文:

IIUC, you could use a slice and assign your value as list:

list_a = [1, 2, 3, 4, 5, 6, 7]

list_a[1:3] = [9]   # list_a[1:3] are elements [2, 3]

print(list_a)

Output: [1, 9, 4, 5, 6, 7]

Note that in python the indices start with 0, thus your slice is 1:3 (indices 1 to 3, excluding 3), see How slicing in Python works for more details.

# indices:  0  1  2  3  4  5  6
list_a  =  [1, 2, 3, 4, 5, 6, 7]
# slice:       x  x 

答案2

得分: 0

我们可以使用列表切片方法:

list_a = [1, 2, 3, 4, 5, 6, 7]
# 这里你想要消除第 2 和 3 个元素,然后用 9 替换它们
index = list_a.index(2)
# 语法:l = l[:index] + ['new_value'] + l[index+2:]
list_a = list_a[:index] + [9] + list_a[index+2:]
print(list_a)

输出:

[1, 9, 4, 5, 6, 7]
英文:

we can use the list slicing method

list_a = [1, 2, 3, 4, 5, 6, 7]
# here you want to eliminate 2,3 elements and replace 9 instead of them
index= list_a.index(2)
# Syntax: l=l[:index]+[‘new_value’]+l[index+2:] 
list_a = list_a[ :index] + [9] + list_a[index+2: ]
print(list_a)

Output:

[1, 9, 4, 5, 6, 7]

答案3

得分: 0

你可以使用列表切片来解决你的问题。示例代码:

# 创建你的列表
list_a = [1, 2, 3, 4, 5, 6, 7]

# 将索引1到3的元素,即第2到第4个元素替换为9
list_a[1:3] = [9]

然后你可以打印列表:

print(list_a)

输出结果:

[1, 9, 4, 5, 6, 7]

请注意,你必须将9放在方括号内。这是因为你只能用可迭代对象替换多个元素。所以,将九放在方括号内,使它成为可迭代对象。不将9放在方括号内将导致TypeError错误。

英文:

You can use list slices to solve your problem. Example code:

#Create your list
list_a = [1, 2, 3, 4, 5, 6, 7]

#Replace the elements from index 1 to 3 i.e. 2nd to 4th element with 9
list_a[1:3] = [9]

Then you can print the list:

print(list_a)

Output:

[1, 9, 4, 5, 6, 7]

Note that you have to put 9 within square brackets. This is because you can replace multiple elements only with an iterable. So, putting nine within square brackets, makes it an iterable object. Not putting 9 within brackets will give a TypeError.

huangapple
  • 本文由 发表于 2023年5月17日 16:39:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76270101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定