简体   繁体   English

替换列表中的元素,Python

[英]Replacing elements in a list, Python

How a value in a list can be replaced? 如何替换列表中的值?

Suppose I have the following list : 假设我有以下列表:

mylist=[1,3,5,7,4]

and I just want to change the value at index 3 ( which would be 7) with, let's say, 9. (the change is not conditioned ) 我只想用9来更改索引3的值(该值为7)。(该更改没有条件)

For earlier versions of python the replace function would work, but how do I do it in Python 3.6? 对于早期版本的python,replace函数将起作用,但是如何在Python 3.6中实现呢?

Console: 安慰:

➜ ~ python3
Python 3.6.2 (default, Aug 03 2017, 16:34:42) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist=[1,3,5,7,4]
>>> mylist[3]=9
>>> mylist
[1, 3, 5, 9, 4]
>>>

Just like that. 就这样

>>> mylist = [1,3,5,7,4]

1 . 1。 The simplest, go to the list index and assign it the new value. 最简单的是,转到列表index并为其分配新值。

>>> mylist[3] = 9
>>> mylist
=> [1, 3, 5, 9, 4]

2 . 2。 Slicing

>>> mylist = mylist[:3] + [9] + mylist[4:]
>>> mylist
=> [1, 3, 5, 9, 4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM