0

I'd like know how can I localize a specific type variable in a set of arrays, that could change its own length structure, i.e:

[[[[11.0, 16.0], [113.0, 16.0], [113.0, 41.0], [11.0, 41.0]], ("I WANNA BE LOCATED", 548967)]]

I just needed to extract the type variable that is a Str in this case:

"I WANNA BE LOCATED"

I tried use "for" loop, but it doesn't help, because possibly in my case, the string might be there in other indices. Is there another way? Maybe with numpy or some lambda?

2 Answers2

2
  1. Flatten the arbitrarily nested list;
  2. Filter the strings (and perhaps bytes).

Example:

from collections.abc import Iterable

li=[[[[11.0, 16.0], [113.0, 16.0], [113.0, 41.0], [11.0, 41.0]], ("I WANNA BE LOCATED", 548967)]]

def flatten(xs):
    for x in xs:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from flatten(x)
        else:
            yield x

>>> [item for item in flatten(li) if isinstance(item,(str, bytes))]
['I WANNA BE LOCATED']
dawg
  • 98,345
  • 23
  • 131
  • 206
1

I'd do it recursively; this, for example, will work (provided you only have tuples and lists):

collection = [[[[11.0, 16.0], [113.0, 16.0], [113.0, 41.0], [11.0, 41.0]], ("I WANNA BE LOCATED", 548967)]]

def get_string(thing):
    if type(thing) == str:
        return thing
    if type(thing) in [list, tuple]:
        for i in thing:
            if (a := get_string(i)):
                return a
    return None

get_string(collection)
# Out[456]: 'I WANNA BE LOCATED'
Swifty
  • 2,630
  • 2
  • 3
  • 21