Python Forum
flattening a list with some elements being lists
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
flattening a list with some elements being lists
#11
It's nice solution using functools.singledispatch, but not supported in python2.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#12
(Aug-06-2018, 10:26 AM)perfringo Wrote: This is the reason I like Python - smart people (like buran) can achieve desired results with minimal and very readable piece of code. I have lot of work to do in smart part
We all are smart people. I just don't know enough. I've got RecursionError and it was said to me that it's because the strings are iterable. Then I saw how can be done for strings. I see it now too. I still don't get it why if I use a generator in the way I've done it I get this error. Yes, strings are iterable but I tried it on a small piece of data.
Something happens internally and I just don't know what it is. If one can explain it, please!
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#13
(Aug-06-2018, 10:44 AM)buran Wrote: It's nice solution using functools.singledispatch, but not supported in python2.
Of course it is, you only need to pip install singledispatch, then
from singledispatch import singledispatch
Reply
#14
i like to have my code, especially functions, work in both Python2 (until at least Python2 EOL) and Python3 (back as far as possible) without using any modules. and if it really needs a module, preferably one that comes in Python itself, and if not that, one that can be installed with pip. i think my own flatten function managed to do that. it was a bit longer, but "simpler" in the sense of not using things like generators an subgenerators. my technique to manage the recursion was sloppy. buran did better and it still meets my goals (like not needing a module). even better is that it doesn't need variable arguments like i used. and even better is that the whole thing is functional.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#15
The advantage of singledispatch is modularity. Custom types can be easily added with their own ways of being flattened.
Reply
#16
I have don this a while ago: https://pastebin.com/1D0J3Sdn

def flat_sequnce_gen(input_list, traverse=None, exclude=None, debug=False):
    traverse = traverse or (list, tuple)
    exclude = exclude or (str, bytes, int, float, complex)
    iterators = [iter(input_list)]
    last = None
    while iterators:
        try:
            current = next(iterators[-1])
        except StopIteration:
            iterators.pop()
            continue
        if isinstance(current, traverse) and not isinstance(current, exclude):
            if last is current:
                yield current
                iterators.pop()
                continue
            iterators.append(iter(current))
            last = current
        else:
            yield current
There is also possibility for improvement.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#17
i went with buran's solution for my function collection.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#18
While reading Python Cookbook, 3rd Edition by David Beazley and Brian K. Jones I stumbled upon recipe 4.14. Flattening a Nested Sequence.

from collections import Iterable

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

items = [1, 2, [3, 4, [5, 6], 7], 8]

# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
    print(x)
Quote:In the code, the isinstance(x, Iterable) simply checks to see if an item is iterable. If so, yield from is used to emit all of its values as a kind of subroutine. The end result is a single sequence of output with no nesting.

The extra argument ignore_types and the check for not isinstance(x, ignore_types) is there to prevent strings and bytes from being interpreted as iterables and expanded as individual characters.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 424 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 470 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  List all possibilities of a nested-list by flattened lists sparkt 1 914 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Checking if a string contains all or any elements of a list k1llcod3 1 1,094 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  user input values into list of lists tauros73 3 1,064 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  returning a List of Lists nafshar 3 1,058 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,611 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  How to change the datatype of list elements? mHosseinDS86 9 1,954 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,112 May-17-2022, 11:38 AM
Last Post: Larz60+
  How to efficiently average same entries of lists in a list xquad 5 2,114 Dec-17-2021, 04:44 PM
Last Post: xquad

Forum Jump:

User Panel Messages

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