0

I have a very long list I'm trying to convert as fast as possible.

Currently I'm doing the following which is very fast compared to a 1 by 1 conversion:

alist = [1,2,3,4, ... 100000]
list_with_unit = alist * ureg('meter')
list_converted = list_with_unit.to(ureg('feet'))

The problem is that if alist contains a None value I will get:

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

Has anybody an idea how to resolve this issue so that for None values I get a None returned?

Francesco Meli
  • 2,484
  • 2
  • 21
  • 52
  • how should it behave when it finds the `None`? – Netwave Jan 28 '19 at 11:37
  • I will update the question – Francesco Meli Jan 28 '19 at 11:39
  • 4
    dont use the list word for variable name, it is a builtin name. – Paritosh Singh Jan 28 '19 at 11:40
  • If you think you can multiply each value in the list by `ureg('meter')` using `list * ureg('meter')`, you are wrong. For this to work, you need to convert your list to a numpy array. Lists don't allow arithmetic operations in this manner – Sheldore Jan 28 '19 at 11:41
  • use `np.ma` module to mask out the `None` values – DrBwts Jan 28 '19 at 11:54
  • @ParitoshSingh, thanks – Francesco Meli Jan 28 '19 at 12:08
  • @Bazingaa, actually from the home page of the package https://pint.readthedocs.io/en/0.9/, you'll see it does list multiplication as I did and it works. I'm not sure if it uses numpy in the background, but I can definitely do what I did without the need to explicitly import numpy. – Francesco Meli Jan 28 '19 at 12:08
  • @pnknrg: Ok, it seems under the hood pint does something to the list to make the arithmetic operation possible. If you try `alist * 2.5` for example, it wont' work – Sheldore Jan 28 '19 at 12:15
  • @Bazingaa, that I know :) – Francesco Meli Jan 28 '19 at 12:23
  • The easiest thing you can do is use numpy and a mask. In fact [it is recommended by pint](https://pint.readthedocs.io/en/latest/numpy.html) that you use numpy arrays for data, unless you have a good reason for not doing so. Alternatively, do you have a reason not to remove the `None` values? – Tarifazo Jan 28 '19 at 13:15

0 Answers0