+ 1
lista de lista
hola, por fa me podran ayudar con esto: [1,2,['a','b'],[10]]) debe retornar [1,2,'a','b',10] como separo cada elemento en un elemento unico?????
3 Answers
+ 8
Pablo Castro ,
here some thoughts how the task can be done:
(i would not recomnend you to use chain, until you are familiar with it)
instead of this we can have a simple code with 2 for loops. this code can solve 1 level of nesting like: [1,2,['a','b'],[10]]
if there are more nested levels to flatten, we need an other approach
- let's say we have an input of: [1,2,['a','b'],[10]]
- to store the final result we need an empty list like result
- we start a for loop (outer loop)
- we have to check the type of each element coming from the outer loop
- if the type of the element is NOT a list, add it to the result list
- otherwise use a second for loop (inner loop)
- take each element coming from the inner loop and add it to the result list
- print the result list
+ 6
please show your attempt. link your code here.
+ 1
def from_iterable(iterables):
# chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
for it in iterables:
for element in it:
yield element
from_iterable([[1,2,[3]],[4]])
<generator object from_iterable at 0x000000679D16D190>
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables:
for element in it:
yield element
chain(*[[1,2,[3]],[4]])
<generator object chain at 0x000000679D16D9E0>