[Tutor] Replace nth item with single value in each nested list

Peter Otten __peter__ at web.de
Fri May 15 10:15:12 EDT 2020


EK Esawi via Tutor wrote:

> Hi All--
> 
> 
> Thank you all for your input. It’s highly appreciated. With your help, I
> managed to produce something that works for me; but only works for nested
> lists with two entries. For more than two entire nested lists, it produces
> only 2 entries nested lists.
> 
> Here is my formula:
> 
> aa=[[x[0],60] if x[1] >= 3 else [x[0],x[1]] for x in a]
> 
> a is my list

You can generalize this a little with slices

aa = [x[:1] + [60 if x[1] >= 3 else x[1]] + x[2:] for x in a]

but as was pointed out this is more complex than the inplace solution,

for x in a:
    if x[1] >= 3:
        x[1] = 60

needs to do more work, and requires more memory. 

If you have numpy around there is another alternative:

b = numpy.array(a)
b[:,1][b[:,1] >= 3] = 60

Very concise, but I'd probably rewrite that with a helper variable

b = numpy.array(a)
c = b[:,1]
c[c>=3] = 60

or transpose the array.






More information about the Tutor mailing list