python怎么更新列表_在python中更新列表元素

在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]:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值