Python replacing numbers in a list

piccolo

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?

Martijn Pieters

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]    

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Replacing groups of numbers from list (python)

From Dev

Replacing end numbers in a string python

From Dev

Python - replacing string/symbol with numbers

From Dev

Python - Replacing characters in a list

From Dev

replacing the values of a list in python

From Dev

Replacing Values in a List with Index in Python

From Dev

Replacing duplicate elements in a list in Python?

From Dev

Replacing python list elements with key

From Dev

Replacing elements in long list Python

From Dev

Replacing parts of strings in a list in Python

From Dev

Cost of replacing an element of a list in python

From Dev

Replacing part of a string in a list in python

From Java

lambda if with list of numbers in python

From Dev

Normalizing a list of numbers in Python

From Dev

Python add numbers in a list

From Dev

Parse list of numbers into list in python

From Dev

Replacing white space inside a list of strings in python

From Dev

Finding and replacing in a list using user input (python)

From Dev

Having trouble when replacing in a list-Python

From Dev

Replacing list comprehensions with pandas and numpy Python

From Dev

Replacing Elements in 3 dimensional Python List

From Dev

finding and replacing elements in a multidimensional list (python)

From Dev

Python: Minimum Numbers in List, Including Repeated Numbers

From Dev

Permutations of a list of input numbers in Python

From Dev

Python CSV multiple numbers in the list

From Dev

python convert bytearray to numbers in list

From Dev

creating list of random numbers in python

From Dev

Return positive numbers of a list in python

From Dev

asking for numbers in python and returning a list

Related Related

HotTag

Archive