1. Check if the list is empty
There is no need to call the Len method to detect if a list is empty, because an empty list evaluates to False.
if Len (mylist): # Do something with my list Else : # The list is empty
You can use the following method instead:
if mylist: # Do something with my list Else : # The list is empty
2. Get the index value of an element at the same time as the iteration list
Sometimes you need to iterate over a list and get the index value for each element. The usual practice is to:
i = 0 for in mylist: # does something with I and element i + = 1
A better approach would be to:
for inch Enumerate (mylist): # Do something with I and element Pass
3. List sorting
Create a persons list:
class Person (object): def __init__ (self, Age): = for in (14, 78, 42)]
If we want to sort the list by age, we can do this:
def Get_sort_key (Element): return Element.age for in sorted (persons, key=Get_sort_key): print"age:" , Element.age
We define a function that returns the attributes that are the sort criteria. and pass this function as a parameter to the sorted function. Because this sort is common, the Python standard library already contains such a function.
from Import Attrgetter # Attrgetter is a high-order function that can return a function for in sorted (persons, Key=attrgetter ('age')): Print " Age : ", Element.age
This makes the code easier to read. When you see the Attrgetter function you will know that it is used to get a property. There are also Itemgetter and Methodcaller methods in the operator module, and I believe you can see their role at a glance.
Some suggestions on the Python collection