[英]Python - Can you use list comprehension to replace the value at a particular list index?
我目前有一堆列表定义如下:
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)
Output
{1: ['new', 2, 3, 4, 5]}
广义形式
old_list = [1, 2, 3, 4, 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)
Output
{3: [1, 2, 'new', 4, 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', 2, 3, 4, 5]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.