-2

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!

jpp
  • 159,742
  • 34
  • 281
  • 339
Akshit A.
  • 27
  • 4

2 Answers2

0

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
bla
  • 1,840
  • 1
  • 13
  • 17
  • Note: his function is actually not the same as round because, for some reason, he's rounding 0.5 *down* instead of *up* – iAdjunct Apr 28 '18 at 19:53
  • Just tested in python3.6 and `round(0.5)` returns `0`. – bla Apr 28 '18 at 19:59
  • 1
    `Python 2.7.10` returns `1.0`. That is weird; Python2's `round` function is consistent with the traditional definition of round, but Python3's implements the round-half-to-even paradigm (https://en.wikipedia.org/wiki/Rounding#Round_half_to_even). – iAdjunct Apr 28 '18 at 20:25
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.

jpp
  • 159,742
  • 34
  • 281
  • 339