mirror of
https://github.com/Mikaela/Limnoria.git
synced 2025-01-30 06:04:21 +01:00
Added flatten.
This commit is contained in:
parent
f4b1884a34
commit
b6608b9643
11
src/fix.py
11
src/fix.py
@ -290,4 +290,15 @@ def itersplit(iterable, isSeparator, yieldEmpty=False):
|
||||
if acc or yieldEmpty:
|
||||
yield acc
|
||||
|
||||
def flatten(seq, strings=False):
|
||||
for elt in seq:
|
||||
if not strings and type(elt) == str or type(elt) == unicode:
|
||||
yield elt
|
||||
else:
|
||||
try:
|
||||
for x in flatten(elt):
|
||||
yield x
|
||||
except TypeError:
|
||||
yield elt
|
||||
|
||||
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:
|
||||
|
@ -240,3 +240,17 @@ class FunctionsTest(unittest.TestCase):
|
||||
self.assertEqual(AL.values(), [2, 3, 4])
|
||||
self.assertEqual(list(AL.itervalues()), [2, 3, 4])
|
||||
self.assertEqual(len(AL), 3)
|
||||
|
||||
def testFlatten(self):
|
||||
def lflatten(seq):
|
||||
return list(flatten(seq))
|
||||
self.assertEqual(lflatten([]), [])
|
||||
self.assertEqual(lflatten([1]), [1])
|
||||
self.assertEqual(lflatten(range(10)), range(10))
|
||||
twoRanges = range(10)*2
|
||||
twoRanges.sort()
|
||||
self.assertEqual(lflatten(zip(range(10), range(10))), twoRanges)
|
||||
self.assertEqual(lflatten([1, [2, 3], 4]), [1, 2, 3, 4])
|
||||
self.assertEqual(lflatten([[[[[[[[[[]]]]]]]]]]), [])
|
||||
self.assertEqual(lflatten([1, [2, [3, 4], 5], 6]), [1, 2, 3, 4, 5, 6])
|
||||
self.assertRaises(TypeError, lflatten, 1)
|
||||
|
Loading…
Reference in New Issue
Block a user