在python中更新成对列表

2024-04-19 05:00:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更新由成对值组成的列表,如下所示:

list = [('n1',1),('n2',2),('n3',3),('n4',4),('n5',5)]

现在我想用n1将值更新为16。所以我试着这样做:

>>> list['n1'] = 16
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str

使用键值类功能访问列表的方法是什么?你知道吗


Tags: most列表calllistfilelasttracebackrecent
3条回答

把它转换成dict

myList = [('n1',1),('n2',2),('n3',3),('n4',4),('n5',5)]
myDict = dict(myList)
myDict['n1'] = 16

另外,不建议使用list作为变量名,因为它是python中built-in function的名称。你知道吗

您可以使用列表:

>>> lst = [('n1', 1), ('n2', 2), ('n3', 3), ('n4', 4), ('n5', 5)]
>>> lst = [('n1', 16) if 'n1' in item else item for item in lst]
>>> lst
[('n1', 16), ('n2', 2), ('n3', 3), ('n4', 4), ('n5', 5)]

使用dict

dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs

d = dict(list)
d['n1'] = 16

注意**不要使用list作为变量名,它将重写内置函数list。你知道吗

相关问题 更多 >