I have a list in python
l=[[0.1,0.2,0.9],[0.3,0.4,0.6],[0.8,0.2,0.8]]
if element <=0.5
, return 0
,
if element > 0.5
, return 1
Hence resulting l should look like:
l=[[0,0,1],[0,0,1],[1,0,1]]
Thanks in advance!
I have a list in python
l=[[0.1,0.2,0.9],[0.3,0.4,0.6],[0.8,0.2,0.8]]
if element <=0.5
, return 0
,
if element > 0.5
, return 1
Hence resulting l should look like:
l=[[0,0,1],[0,0,1],[1,0,1]]
Thanks in advance!
Check out round
.
>>> l=[[0.1,0.2,0.9],[0.3,0.4,0.6],[0.8,0.2,0.8]]
>>> [[round(x) for x in i] for i in l]
[[0, 0, 1], [0, 0, 1], [1, 0, 1]]
As mentioned by @iAdjunct in the comments and discussed in this question, if working on python 2 this will not result in desired output.
That is because they adopt different rounding methods. The difference can be illustrate with these examples:
Python2:
>>> round(0.5)
1.0
Python3
>>> round(0.5)
0
There are couple of ways you can do this; either in pure Python via list comprehension or in a vectorised fashion using a 3rd party library.
Pure Python
You can use a nested list comprehension.
l = [[0.1,0.2,0.9],[0.3,0.4,0.6],[0.8,0.2,0.8]]
res = [[0 if i <= 0.5 else 1 for i in row] for row in l]
[[0, 0, 1], [0, 0, 1], [1, 0, 1]]
Vectorised alternative
This uses the 3rd party library numpy
.
import numpy as np
res = np.where(np.array(l) <= 0.5, 0, 1)
array([[0, 0, 1],
[0, 0, 1],
[1, 0, 1]])
Note on rounding
Comparing floats with floats is difficult due to the nature of float
not storing numeric data in base-10 format. See Is floating point math broken? for more details. This is a problem even with the above methods.
This means you may have to take particular care for boundary cases, if this matters to you.