python - Best way to replace values in a list based on many indexes -
i have list this:
l = [1,2,3,4,5,6,7,8,9,10] idx = [2,5,7]
i want replace values in l 0, using indexes idx. do:
for in idx: l[i] = 0
this give: l = [1, 2, 0, 4, 5, 0, 7, 0, 9, 10]
is there better, faster, more pythonic way. small example, if have huge lists?
i think fine. write list comprehension, this:
[v if not in idx else 0 i, v in enumerate(l)]
or change in place iterating on l
for i, v in enumerate(l): if in idx: l[i] = 0
but find harder read, , slower. don't think other solution beat yours significant margin, ignoring cpu caching.
Comments
Post a Comment