Flattening lists
Rhamphoryncus
rhamph at gmail.com
Sat Feb 7 04:06:06 EST 2009
On Feb 6, 10:21 pm, rdmur... at bitdance.com wrote:
> Quoth Mensanator <mensana... at aol.com>:
> > def flatten(listOfLists):
> > return list(chain.from_iterable(listOfLists))
>
> Python 2.6.1 (r261:67515, Jan 7 2009, 17:09:13)
> [GCC 4.3.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from itertools import chain
> >>> list(chain.from_iterable([1, 2, [3, 4]]))
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: 'int' object is not iterable
> >>> list(chain(*[1, 2, [3, 4]]))
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: 'int' object is not iterable
> >>> list(chain.from_iterable(['abcd', 'efg', [3, 4]]))
> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 3, 4]
What usecase do you have for such inconsistently structured data?
If I'm building a tree I use my own type for the nodes, keeping them
purely internal, so I can always use isinstance without worrying about
getting something inconvenient passed in.
More information about the Python-list
mailing list