[英]Change the value of a list's element
I have created a list holding various values. 我创建了一个包含各种值的列表。 However i wanted to know how i could update/replace a piece of data in a list of a specific position.
但是我想知道如何更新/替换特定位置列表中的数据。 For example if i had a list as follows:
[hello, goodbye, welcome, message]
and i wanted to replace the string in position 2
with the following string: 'wave'
. 例如,如果我有一个列表如下:
[hello, goodbye, welcome, message]
,我想用以下字符串替换位置2
的字符串: 'wave'
。 how would i do that?? 我该怎么办? i tried the code below, but it shifts the values to the right and inserts a new piece of data where the position is given:
我尝试了下面的代码,但是它将值向右移动,并在给出位置的位置插入了新数据:
MyList = ['hello', 'goodbye', 'welcome', 'message']
MyList.insert(2, 'wave')
Lists are mutable , which means you can alter them in place. 列表是可变的 ,这意味着您可以就地更改它们。 Therefore you can simple assign a new value to index 2:
因此,您可以简单地为索引2指定一个新值:
>>> lst = range(10)
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst[2] = "new value"
>>> lst
[0, 1, 'new value', 3, 4, 5, 6, 7, 8, 9]
dicts
are also mutable: dicts
也是易变的:
>>> d = {1:'a',2:'b'}
>>> d[2] = "new value"
>>> d
{1: 'a', 2: 'new value'}
However, strings and tuples ARE NOT . 但是,字符串和元组不是 。 You can iterate through them which sometimes causes confusion, (especially the sub-string notation vs. slicing)
您可以遍历它们,这有时会引起混淆(尤其是子字符串表示法和切片)
>>> aString = "Hello, my name is Dave"
'my '
>>> aString[7:9]
'my'
>>> aString[7:9] = "MY"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Similarly, 同样的,
>>> tup = (1,2,3)
>>> tup[0]
1
>>> tup[0] = 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
For strings, you can "cheat" by converting them into a list ( split()
), mutating them, then putting them back into a string ( join()
), but this is not actual mutation of the string in place 对于字符串,您可以通过将其转换为列表(
split()
),对其进行变异,然后将其放回字符串( join()
)中来“作弊”,但这并不是实际的字符串变异
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.