问题描述
我目前有一堆定义如下的列表:
old_list = [1,2,3,4,5]
我目前正在替换该列表的第一个元素,然后通过执行以下操作将列表的内容放入字典(其中键是旧元素 0 值):
old_value = old_list[0]
old_list[0] = 'new value'
test_dict[old_value] = old_list
我想知道,这是实现此目的的最佳方法吗?我想知道是否有办法通过列表理解来提高效率,使其看起来更像这样:
test_dict[old_list[0]] = [i for idx,i in enumerate(old_list) if '''relevant conditions to replace element 0''']
解决方法
这是一种方法
代码
old_list = [1,2,3,4,5]
new_value = 'new'
test_dict = {}
test_dict[old_list[0]] = [new_value] + old_list[1:]
print(test_dict)
输出
{1: ['new',5]}
广义形式
old_list = [1,5]
idx = 2
new_value = 'new'
test_dict = {}
test_dict[old_list[idx]] = old_list[:idx] + [new_value] + old_list[idx+1:]
print(test_dict)
输出
{3: [1,'new',5]}
,
可以通过解包实现可读的形式:
head,*tail = old_list
# if test_dict already exists
test_dict[head] = ["new value"] + tail
# otherwise
test_dict = {head: ["new value"] + tail}
# {1: ['new value',5]}