In this type of operation, using generators is a very efficient solution. With this we avoid the use of any intermediate variable, chain concatenation and the use of comparisons that make the code much more inefficient, besides having to write much less code.
One option is to use itertools.islice()
next to a generator that returns the elements from the matrix flattened to do this:
import itertools
n = int(input("largo del string: "))
a = [["w","e","r"],["t","d","f"],["e","h","j"]]
s = ''.join(itertools.islice((j for i in a for j in i), n))
print(s)
Since in this case the 'slice' on the generator is always 0:n
we can do without itertools.islice()
and simply do:
n = int(input("largo del string: "))
a = [["w","e","r"],["t","d","f"],["e","h","j"]]
gen = (caracter for lista in a for caracter in lista)
s = ''.join(next(gen) for _ in range(n))
print(s)
Exit examples:
length of string: 2
we
length of string: 5
wertd
length of the string: 8
wertdfeh
length of the string: 20
wertdfehj
If your list is relatively small and your n are going to be generally large with respect to the entry list the conversion to list is more efficient at run time (not in memory usage) than implement generators:
res = ''.join([caracter for lista in a for caracter in lista])[:n]
In this case list compression is used but there are other approaches like the solution proposed by José Hermosilla Rodrigo (see comment below for this answer) using itertools.chain.from_iterable
or @Alexis' answer, which are very good in terms of time execution and simplicity of code in this assumption (lists not excessively extensive with n
relatively large).