Python - 您可以使用列表理解来替换特定列表索引处的值吗?

问题描述

我目前有一堆定义如下的列表:

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]}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...