我想替换那些list1
的元素,其索引存储在列表indices
中list2
元素。以下是当前的代码:Python单行要替换一个列表索引
j=0
for idx in indices:
list1[idx] = list2[j]
j+=1
是否有可能写一行程序使用lambda函数或列表理解上述四行?
编辑
list1
包含浮点值
list2
包含浮点值
indices
包含0
和len(list1)
我想替换那些list1
的元素,其索引存储在列表indices
中list2
元素。以下是当前的代码:Python单行要替换一个列表索引
j=0
for idx in indices:
list1[idx] = list2[j]
j+=1
是否有可能写一行程序使用lambda函数或列表理解上述四行?
编辑
list1
包含浮点值
list2
包含浮点值
indices
包含0
和len(list1)
# A test case
list1 = [0, 1, 2, 3, 4, 5, 6]
list2 = ['c', 'e', 'a']
indices = [2, 4, 0]
# Use conditional expressions
new_list = [list2[indices.index(idx)] if idx in indices else v for idx, v in enumerate(list1)] # idx2 = indices.index(idx), for list2
print(new_list)
# Output
['a', 1, 'c', 3, 'e', 5, 6]
嗨,这个看起来不正确。为什么选择'list2'的'idx'条目? 'list1 [idx]'条目将被替换为'list2'条目(以串行方式)。 – vvy
@vvy,thx,我用一个例子编辑了我的答案。结果与您的原始代码一致。 – SparkAndShine
的整数这不是那么漂亮,但你可以解决这个问题是这样的:
map(list1.__setitem__, indices, list2)
你会说它在Python 3中不起作用。 – vaultah
虽然很聪明,但PEP 20可能会反对。 – boardrider
我同意你们,但OP要求提供“单线”,我交付了它:) – zoubida13
虽然它不是一个衬垫,这里是我认为是更具可读性的替代:
for i, v in zip(indices, list2):
list1[i] = v
当然,如果你将'list1 [i] = v'移动到'for'循环的同一行上,那么它就是1行,这绝对是最干净的答案! –
没有,列表内涵不能修改现有列表。 –
你能举一个'list1','list2'和'incides'包含的例子吗? –
@MorganThrapp创建新列表的选项是* open *! – vvy