The example described in this article comes from an independent software developer, Alex Marandon, who has introduced several practical tips on Python Collection in his blog to share with you. For everyone to learn from the use. Specifically as follows:
1. Determine whether a list is empty
The traditional way:
If Len (mylist):
# do something and my list
else:
# The ' list is empty
Because an empty list itself is equivalent to False, you can directly:
If mylist:
# do something and my list
else:
# The ' list is empty
2. Retrieve the index while traversing the list
The traditional way:
i = 0 for
element in MyList:
# does something with I and element
i = 1
This is more concise:
For I, element in enumerate (mylist):
# does something with I and element
pass
3.list sorting
It is a common practice to sort by a property in a list that contains an element. For example, here we first create a list that contains the person:
class Person (object):
def __init__ (self, Age):
Self.age = age
persons = [Person (age) to age in (14, 78, 42)]
The traditional way is:
def get_sort_key (Element): Return
element.age
to element in sorted (persons, Key=get_sort_key):
print " Age: ", element.age
A more concise and more readable approach is to use the operator module in the Python standard library:
From operator import Attrgetter for
element in sorted (persons, Key=attrgetter (' Age ')):
print "Age:", Element.age
The Attrgetter method first returns the Read property value as a parameter to the sorted method. The operator module also includes Itemgetter and Methodcaller methods, which act as literal meanings.
4. Grouping elements in Dictionary
Similar to the above, first create Persons:
class Person (object):
def __init__ (self, Age):
Self.age = age
persons = [Person (age) to age in (78, 14, 78, 4 2, 14)]
If we're going to group by age now, one way is to use the in operator:
Persons_by_age = {} for person in
persons: Age
= Person.age
if age in Persons_by_age:
persons_by_age[age ].append (person)
else:
persons_by_age[age] = [person]
assert Len (persons_by_age[78]) = = 2
In contrast, the approach to using the Defaultdict method in the collections module is more readable:
From collections import defaultdict
persons_by_age = defaultdict (list) for person in
persons:
persons_ By_age[person.age].append (person)
Defaultdict will use the accepted parameters to create the corresponding value for each nonexistent key, where we pass the list, so it will create a value for each key of the list type.
The example of this article is only the program framework, and the specific function needs to be perfected by the readers according to their own application environment. I hope the examples described in this article will help you learn about Python.