.feed-links {display:none !important;} -->

Python list understandings

 A good developer will always seek to increase their productivity over time. There are python tricks which allow to optimize the code .

One of these tricks is the list comprehension (or list comprehension or list comprehension ).

The idea is simple: simplify the code to make it more readable and therefore faster to write and easier to maintain.

Syntax

new_list  =  [ function ( item )  for  item  in  list  if  condition ( item )]

Filter a list

Let's take an example of a list:

>>>  a  =  [ 1 , 4 , 2 , 7 , 1 , 9 , 0 , 3 , 4 , 6 , 6 , 6 , 8 , 3 ]

We want to filter the values ​​in this list and keep only those whose value is greater than 5:

>>>  b  =  [] 
>>>  for  x  in  a : 
...      if  x  >  5 : 
...          b . append ( x ) 
...  
>>>  b 
[ 7 ,  9 ,  6 ,  6 ,  6 ,  8 ]

It's possible to do exactly what this block of code does in a single line:

>>>  [ x  for  x  in  a  if  x  >  5 ] 
[ 7 ,  9 ,  6 ,  6 ,  6 ,  8 ]

Execute a function on each item of a list

Let's take the example of a string to integer conversion of several items:

> > > Items =  [ "5" ,  "10" ,  "15" ] 
> > > items =  [ int ( x )  for x in items ] 
> > >  print (items)
 [ 5 ,  10 ,  15 ]

No comments:

Post a Comment