аватар question@mail.ru · 01.01.1970 03:00

Break the elements of the list

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 ']))     

I explain - redCe accepts the input function that combines the results of breaking the list with the function of map . 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 loop 

from the answer @jfs really works quickly:

  $ python3 -m Timeit    1000000  loops, Best of  3 :  0.452  usec per loop 

the 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 loop    

Map-ReedCe is the slowest. Why am I using it? Because I like chains of calls. The rest & mdash; Taste. However, even Guido hates redce (and carried it to functools in python3 )

  $ Python3 -m Timeit    100000  loops, Best of  3 :  2.16  usec per loop    

the 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                                      

Latest

Similar