Tips for using collections in Python
- 2020-04-02 13:59:08
- OfStack
The examples in this article are from Alex Marandon, an independent software developer, who has introduced several useful tips on Python collections in his blog. For your reference. The details are as follows:
1. Determine if a list is empty
The traditional way:
if len(mylist):
# Do something with my list
else:
# The list is empty
Since an empty list itself is equal to False, we can directly:
if mylist:
# Do something with my list
else:
# The list is empty
2. Get the index while traversing the list
The traditional way:
i = 0
for 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
3. Sort the list
Sorting by an attribute in a list of elements is a common operation. For example, here we create a list of people:
class Person(object):
def __init__(self, age):
self.age = age
persons = [Person(age) for age in (14, 78, 42)]
The traditional approach is:
def get_sort_key(element):
return element.age
for element in sorted(persons, key=get_sort_key):
print "Age:", element.age
A more concise and readable approach is to use the operator module from the Python standard library:
from operator import attrgetter
for element in sorted(persons, key=attrgetter('age')):
print "Age:", element.age
The attrgetter method returns the read attribute value first and is passed to the sorted method as an argument. The operator module also includes the itemgetter and methodcaller methods, which do exactly what they say.
Group elements in a Dictionary
Similar to the above, create Persons:
class Person(object):
def __init__(self, age):
self.age = age
persons = [Person(age) for age in (78, 14, 78, 42, 14)]
Now if we want to group by age, 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
The approach using the defaultdict method in the collections module is more readable by comparison:
from collections import defaultdict
persons_by_age = defaultdict(list)
for person in persons:
persons_by_age[person.age].append(person)
Defaultdict will create a value for each key that does not exist using the parameters it accepts. In this case, we are passing a list, so it will create a value of type list for each key.
The example in this article is only a program framework, and the specific functions still need to be improved by the reader according to their own application environment. Hopefully, the examples described in this article will help you learn Python.