Python Forum
[solved] list of list with one or more empty one - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: [solved] list of list with one or more empty one (/thread-40046.html)



[solved] list of list with one or more empty one - paul18fr - May-23-2023

Hi

Without using a loop, is there a way to find an empty list as showing in the following example?

The idea is to find the location and to replace it by a value (such as -1 or zero for example) prior to chnage it to an array

import numpy as np

M = [[1], [], [5]]
Mprime = np.asarray(M, dtype=np.uint32)
logical error:
Error:
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (3,) + inhomogeneous part.
Thanks for your suggestion

Paul


RE: list of list with one or more empty one - Gribouillis - May-24-2023

(May-23-2023, 05:39 PM)paul18fr Wrote: Without using a loop
Why not using a loop?

You can try itertools, for example
>>> from itertools import filterfalse
>>> M = [[1], [], [5]]
>>> a = next(filterfalse(None, M))
>>> a
[]
>>> a.append(0)
>>> M
[[1], [0], [5]]
I'm not sure you gain anything.


RE: list of list with one or more empty one - paul18fr - May-24-2023

Quote:Why not using a loop?
I'm using a list comprehension so far, and in a list of more than a million of components, performance falls of about 25% Cry ; it looks like:

Mprime = [[0] if n == [] else n for n in M]
Let me trying itertools

Paul


RE: list of list with one or more empty one - Gribouillis - May-24-2023

(May-24-2023, 06:55 AM)paul18fr Wrote: Mprime = [[0] if n == [] else n for n in M]
Try this perhaps
Mprime = [n or [0] for n in M]
or if you dont mind having shared lists
x = [0]
Mprime = [n or x for n in M]
Or don't build a list, use a generator
from itertools import chain
x = [0]
Mprime =  Mprime = np.fromiter(chain.from_iterable(n or x for n in M), dtype=np.uint32)
Mprime = Mprime.reshape((Mprime.size, 1))



RE: list of list with one or more empty one - paul18fr - May-24-2023

Thanks Gribouillis for the support and for all advices, it has been helpfull.


RE: [solved] list of list with one or more empty one - jeffreyteague - Oct-04-2023

Nice, thanks for share with us. Beacause i have same problem