Python Forum
[solved] list of list with one or more empty one
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[solved] list of list with one or more empty one
#1
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
Reply
#2
(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.
Reply
#3
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
Reply
#4
(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))
Reply
#5
Thanks Gribouillis for the support and for all advices, it has been helpfull.
Reply
#6
Nice, thanks for share with us. Beacause i have same problem
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [Solved] How to refer to dataframe column name based on a list lorensa74 1 2,282 May-17-2021, 07:02 AM
Last Post: lorensa74
  convert a list of string+bytes into a list of strings (python 3) pacscaloupsu 4 10,881 Mar-17-2020, 07:21 AM
Last Post: markfilan
  search for a part of strinf from list in another list ! evilcode1 3 3,215 Oct-29-2018, 12:07 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020