在Python中,列表和字典是可变的,通过引用传递,字符串、数字和元组是不可变的,并且是通过值传递的。在
因此,如果在l:中使用forx遍历int或string的列表,则无法更改它们,因为x是int或string的实际值。在In [17]: l = [1, 2, 3, 4, 5]
In [18]: for x in l:
....: x = 0
....:
In [19]: l
Out[19]: [1, 2, 3, 4, 5]
但是,当你有一个字典列表时,一切都会改变:
^{pr2}$
因此,原始示例的工作原理与您编写的一样,您可以更改列表中的字典项,但不能以相同的方式更改类型,因为它只是一个字符串列表。在In [14]: my_list = [
....: {"id": 1 ,"number":12, "name": "test1", "type":["read"]},
....: {"id": 1 ,"number":12, "name": "test2","type":["write"]},
....: {"id": 1 ,"number":12, "name": "test3","type":["read", "write"]}
....: ]
In [15]: for item in my_list:
....: item["name"] = "Just an example string"
....: for element in item["type"]:
....: element = "Type example"
....:
In [16]: my_list
Out[16]:
[{'id': 1, 'name': 'Just an example string', 'number': 12, 'type': ['read']},
{'id': 1, 'name': 'Just an example string', 'number': 12, 'type': ['write']},
{'id': 1,
'name': 'Just an example string',
'number': 12,
'type': ['read', 'write']}]
In [17]:
这里有一个更像Python的解决方案:In [35]: for item in my_list:
....: item["name"] = "Just an example string"
....: item["type"] = ["Type Example" for element in item["type"]]
....:
In [36]: my_list
Out[36]:
[{'id': 1,
'name': 'Just an example string',
'number': 12,
'type': ['Type Example']},
{'id': 1,
'name': 'Just an example string',
'number': 12,
'type': ['Type Example']},
{'id': 1,
'name': 'Just an example string',
'number': 12,
'type': ['Type Example', 'Type Example']}]
In [37]: