Hello!
Tell me, please, how can you break the catch list ['1', '22', '333'] by symbols, i.e. To get a list of ['1', '2', '2', '3', '3', '3']
thanks in advance!
question@mail.ru
·
01.01.1970 03:00
Hello!
Tell me, please, how can you break the catch list ['1', '22', '333'] by symbols, i.e. To get a list of ['1', '2', '2', '3', '3', '3']
thanks in advance!
answer@mail.ru
·
01.01.1970 03:00
In the functional region in one line:
redce ( map ( lambda x: line (x), [ '' 1 ', ' ', '' 333 ']))is the slowest. Why am I using it? Because I like chains of calls. The rest & mdash; Taste. However, even Guido hatesI explain -
redCe accepts the input function that combines the results of breaking the list with the function ofmap .map takes a function and the initial array to the input, this function is performed over each element of the array. The same can be expressed by the following code:& gt; & gt; result_list = [] & gt; & gt; & gt; for x in [ '' 1 ', ' '22' , '' 333 ']: ... for y in list (x): ... result_list.append (y) ... & gt; & gt; & gt; print (result_list) [ '' 1 ', ' 2 ', ' 2 ', '' 3 ', ' '3' , '' 3 ']
comparison of the speed of the proposed options:
the option using the option using
Join and the association in the line of the result devoted everyone. It is not surprising & mdash; All operations are fast here. Will work with any iterable objects:$ python3 -m timeit "" List ('. `` Join ([' 1 ',' 22 ',' 333 '])) "" 1000000 loops, Best of 3 : 0.318 usec per loopfrom the answer @jfs really works quickly:
$ python3 -m Timeit 1000000 loops, Best of 3 : 0.452 usec per loopthe option using
sum takes third place in speed, but in my opinion, it loses in intuitiveness:Class = "" Data -Highlighted = ""> $ python3 -m timeit "" sum ([list (i) for i in ['1', '22', '333']], []) "" 1000000 loops, Best of 3 : 0.984 usec per loopMap-ReedCe
redce (and carried it to functools in python3 ) $ Python3 -m Timeit 100000 loops, Best of 3 : 2.16 usec per loopthe option C
collection covers all the cases when the transmitted object can be unexplored (number, for example), but the price for such & mdash; High execution time: $ python3 -m timeit "Import Collectionsdef it (Obj): if IF ISINSTANCE (Obj, Collections.iterable): for OB in Obj: IF IsinStance (OB, Collections.iterable) and Len (OB) & GT; 1: yield from it (OB) Else: Yield Ob Else: YILELD OBJLIST (['1', 2, [2, 44, '123', ('QWE')], 2])) "" 100000 loops, Best of 3 : 14.6 usec per loop