0

给定一个字典,例如:

sample_dict = {'test':['a', 'b', 'c', 'd', 'e']}

如何用其他内容更改列表中的项目。

例子:

def replace_item(sample_dict, item, new_item):
      pass

>>> replace_item({'test':['a', 'b', 'c', 'd', 'e']}, 'd', 'f')
>>> {'test':['a', 'b', 'c', 'f', 'e']}
4

2 回答 2

1

您可以简单地检索列表并对其进行修改,因为字典只存储对列表的引用,而不是列表本身。

于 2013-11-10T02:02:50.387 回答
0
sample_dict = {'test': ['a', 'b', 'c', 'd', 'e']}

def replace_item(sample_dict, item, new_item):
    list = sample_dict['test']
    list[list.index(item)] = new_item

replace_item(sample_dict, 'd', 'f')
# {'test': ['a', 'b', 'c', 'f', 'e']}
于 2013-11-10T02:10:40.670 回答