This article mainly introduces some advanced usage methods of list in Python. It is the basic knowledge of getting started with Python. For more information, see
Determines whether a list is empty.
Traditional methods:
if len(mylist): # Do something with my listelse: # The list is empty
Because an empty list is equivalent to False, you can directly:
if mylist: # Do something with my listelse: # The list is empty
Retrieve indexes while traversing the list
Traditional methods:
i = 0for element in mylist: # Do something with i and element i += 1
This is more concise:
for i, element in enumerate(mylist): # Do something with i and element pass
List sorting
Sorting by attribute in a list containing an element is a common operation. For example, here we first create a list containing person:
class Person(object): def __init__(self, age): self.age = agepersons = [Person(age) for age in (14, 78, 42)]
The traditional method is:
def get_sort_key(element): return element.agefor element in sorted(persons, key=get_sort_key): print "Age:", element.age
A more concise and readable method is to use the operator module in the Python Standard Library:
from operator import attrgetterfor element in sorted(persons, key=attrgetter('age')): print "Age:", element.age
The attrgetter method first returns the read property value as a parameter and passes it to the sorted method. The operator module also includes the itemgetter and methodcaller methods.
List Parsing
Python has a very interesting function, that is, list parsing, which is like this:
>>> squares = [x**2 for x in range(1,10)]>>> squares[1, 4, 9, 16, 25, 36, 49, 64, 81]
Are you surprised to see this result? This is python, and the pursuit of concise and elegant python!
The official documentation provides a description of list parsing:
List comprehensions provide a concise way to create lists. common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
Do you still remember the question mentioned above?
Returns a positive integer less than 100 that can be divisible by 3.
We use the following methods:
aliquot = []for n in range(1,100): if n%3 == 0: aliquot.append(n)print aliquot
Okay. If you use list to parse and rewrite the data, it will be like this:
>>> aliquot = [n for n in range(1,100) if n%3==0]>>> aliquot[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
Shocked. Absolutely awesome X!
In fact, it is not only a list composed of numbers, but can be operated in this way. After restoring your excitement, read the following code and find out the charm of list parsing.
>>> Mybag = ['glass ', 'apple', 'greenleaf'] # Some have leading spaces and some have trailing spaces >>> [one. strip () for one in mybag] # Remove spaces before and after elements ['glass ', 'apple', 'greenleaf']
Enumerate
This is an interesting built-in function. We could have used for I in range (len (list) to get each element number of a list, then, you can use list [I] to obtain the element. What if I want to get the element numbers and elements at the same time? This is the case:
>>> For I in range (len (week )):... print week [I] + 'is' + str (I) # note that I is of the int type. If it is connected to the previous one with +, it must be of the str type... monday is 0 Sunday is 1 Friday is 2
Python provides a built-in function enumerate to implement similar functions.
>>> for (i,day) in enumerate(week):... print day+' is '+str(i)... monday is 0sunday is 1friday is 2
It is an interesting built-in function. It mainly provides a simple and quick method.
This is what the official documentation says:
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. the next () method of the iterator returned by enumerate () returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:
By the way, copy a few examples for the audience to enjoy. It is best to experiment.
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']>>> list(enumerate(seasons))[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]>>> list(enumerate(seasons, start=1))[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]