简体   繁体   English

在给定索引处将给定值分配给列表的元素

[英]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.

相关问题 根据给定的索引合并列表中的元素 - Merge elements in list based on given indices 从给定列表和给定索引中提取列表 - Extract list from given list and given indices 用Python中的新值替换替换索引中给定位置的列表中的元素 - Replacing the elements in list at the positions given in replacement indices with new value in Python 如何有效地从numpy数组中提取由其索引给出的元素列表? - How to extract a list of elements given by their indices from a numpy array efficiently? numpy 函数将数组元素设置为给定索引列表的值 - numpy function to set elements of array to a value given a list of indices 如何用给定的值列表和索引列表填充 python 中的数组? - How to fill an array in python with given list of values and list of indices? 给定索引列表时从列表中获取值的优化方法 - optimized way to get values from list when list of indices given 给定一个列表和一个位掩码,如何返回True为真的索引值? - Given a list and a bitmask, how do I return the values at the indices that are True? 在给定数据框值或索引列表的情况下,如何屏蔽数据框 - How to mask a dataframe given a list of values or indices in the dataframe 按给定的索引顺序对列表进行排序 - Sort list by given order of indices
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM