[英]Assigning given values to elements of a list at given indices
Given some inputs 给定一些输入
L=[0]*5
L1=[2,3]
L2=[12,13]
my required result is: 我要求的结果是:
L=[0,0,12,13,0]
I know how to get this by "brute-force", but my question is, is there a "Pythonic" way to get it, eg with a list comprehension? 我知道如何通过“蛮力”来获取它,但是我的问题是,是否有一种“ Pythonic”的方式来获取它,例如使用列表理解?
Try this: 尝试这个:
import numpy as np
L=np.zeros(5)
L1=np.array([2,3])
L2=np.array([12,13])
L[L1] = L2
print L
# array([ 0., 0., 12., 13., 0.])
Not sure if this is enough pythonic for you: 不知道这对您来说是否足够pythonic:
>>> for i,j in enumerate(L1):
... L[j]=L2[i]
...
>>> L
[0, 0, 12, 13, 0]
and using list comprehension: 并使用列表理解:
>>> [L[i] if i not in L1 else L2[L1.index(i)] for i in range(len(L))]
[0, 0, 12, 13, 0]
我认为这不是pythonic,但这是列表理解。
[l.__setitem__(i, l2.pop(0)) for i in l1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.