给定一个字典,例如:
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']}
给定一个字典,例如:
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']}
您可以简单地检索列表并对其进行修改,因为字典只存储对列表的引用,而不是列表本身。
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']}