piccolo
piccolo

Reputation: 2217

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 None items to be replaced with random numbers in the list that are not themselves a None. 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?

Upvotes: 2

Views: 327

Answers (5)

Vivek Sable
Vivek Sable

Reputation: 10213

  1. Get any value from a list except None. I use max function to get this.
  2. Check max value is not None
  3. Use list comprehension to create new list which replace None value with max value.

Demo:

>>> listP = [ 2.5,  3,  4, None, 4, 8.5, None, 7.3]
>>> l_max = max(listP)
>>> if l_max:
...     listP = [n if n is not None else max(listP) for n in listP]
... 
>>> listP
[2.5, 3, 4, 8.5, 4, 8.5, 8.5, 7.3]
>>> 
  1. max is inbuilt function.
  2. List Comprehension

Upvotes: -1

Selcuk
Selcuk

Reputation: 59184

You can filter the list first to construct a list of not-None values and then randomly choose from it using choice:

import random

listP = [ 2.5,  3,  4, None, 4, 8.5, None, 7.3]
listR = filter(lambda x: x is not None, listP)
print([l if l is not None else random.choice(listR) for l in listP])

result:

[2.5, 3, 4, 7.3, 4, 8.5, 4, 7.3]

Upvotes: 1

gtlambert
gtlambert

Reputation: 11961

You could use the following:

import random

listP = [2.5,  3,  4, None, 4, 8.5, None, 7.3]
numbers = [num for num in listP if num is not None]
answer = [el if el is not None else random.choice(numbers) for el in listP]
print(answer)

Sample Output

[2.5, 3, 4, 3, 4, 8.5, 8.5, 7.3]

This creates a numbers list by filtering out the None values from listP. It then uses a list comprehension with random.choice() to fill None values with a random choice from numbers.

Upvotes: 0

Alexander Trakhimenok
Alexander Trakhimenok

Reputation: 6278

Use list comprehensions

>>> [x if x else 'WHATEVER' for x in [ 2.5, 3, 4, None, 4, 8.5, None, 7.3]] [2.5, 3, 4, 'WHATEVER', 4, 8.5, 'WHATEVER', 7.2999999999999998]

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121844

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]    

Upvotes: 5

Related Questions