Imran Rashid Imran Rashid - 2 years ago 94
Python Question

Python replacing numbers in a list

Hi I have a list of numbers with some 'None''s in them that I want to replace with other numbers in the list that are not 'None'.

For example, for the list below:

listP = [ 2.5, 3, 4, None, 4, 8.5, None, 7.3]

I want the two
items to be replaced with random numbers in the list that are not themselves a
. So in this example the None could be replaced by 2.5 or 3 or 4 or 8.5 or 7.3.

Is there anyway to do this in one line of code?

Answer Source

You'll need to use two steps; extract the non-None values for random.choice() to pick from, then use a list comprehension to actually pick the random values:

import random

numbers = [n for n in listP if n is not None]
result = [n if n is not None else random.choice(numbers) for n in listP]    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download