Ruby a une méthode appelée aplatir qui aplatit un tableau imbriqué en un tableau unidimensionnel, mais je veux parfois l'utiliser en python, alors j'ai essayé de savoir quel type de méthode il existe.
Chose que tu veux faire
>>> flatten([[1, 2], [3, [4, 5]]])
[1, 2, 3, 4, 5]
>>> flatten([1, [2, 3], [[4, [5, 6]], 7]])
[1, 2, 3, 4, 5, 6, 7]
http://qiita.com/kento1218@github/items/f3baf574aadb3d1cbeae
J'ai essayé d'en faire une fonction de générateur en me référant à la méthode trouvée dans Qiita.
Pour lister, il doit être quelque chose comme list (flatten ([[1, 2], [3, [4, 5]]]))
.
def flatten(data):
for item in data:
if hasattr(item, '__iter__'):
for element in flatten(item):
yield element
else:
yield item
def flatten(data):
return (element
for item in data
for element in (flatten(item) if hasattr(item, '__iter__') else [item]))
def flatten(data):
return [element
for item in data
for element in (flatten(item) if hasattr(item, '__iter__') else [item])]
Je l'ai trouvé ici. http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
from compiler.ast import flatten
>>> data = [[1, 2], [3], [4, 5, [6]]]
>>> sum(data, [])
[1, 2, 3, 4, 5, [6]]
Dans Ruby, vous pouvez spécifier la profondeur à aplatir, j'ai donc essayé de la supporter.
flatten.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def flatten(data, depth=-1):
"""
flatten(data) -> list
flatten(data, depth) -> list
Return flatted data of list or tupple as list.
>>> data = [[1, 2], [3, [4, 5, [6]]]]
>>> flatten(data)
[1, 2, 3, 4, 5, 6]
>>> flatten(data, 0)
[[1, 2], [3, [4, 5, [6]]]]
>>> flatten(data, 1)
[1, 2, 3, [4, 5, [6]]]
>>> flatten(data, 2)
[1, 2, 3, 4, 5, [6]]
>>> flatten(data, 3)
[1, 2, 3, 4, 5, 6]
"""
return [element
for item in data
for element in (flatten(item, depth - 1)
if depth != 0 and hasattr(item, '__iter__')
else [item])
]
$ python -m doctest -v flatten.py
Trying:
data = [[1, 2], [3, [4, 5, [6]]]]
Expecting nothing
ok
Trying:
flatten(data)
Expecting:
[1, 2, 3, 4, 5, 6]
ok
Trying:
flatten(data,0)
Expecting:
[[1, 2], [3, [4, 5, [6]]]]
ok
Trying:
flatten(data, 1)
Expecting:
[1, 2, 3, [4, 5, [6]]]
ok
Trying:
flatten(data, 2)
Expecting:
[1, 2, 3, 4, 5, [6]]
ok
Trying:
flatten(data, 3)
Expecting:
[1, 2, 3, 4, 5, 6]
ok
1 items had no tests:
flatten
1 items passed all tests:
6 tests in flatten.flatten
6 tests in 2 items.
6 passed and 0 failed.
Test passed.
Recommended Posts