Tips for using collection in Python

Source: Internet
Author: User
The example presented in this article is from an independent software developer Alex Marandon, who has introduced several practical tips on Python Collection in his blog to share with you. For you to learn from the use of reference. Specific as follows:

1. Determine if a list is empty

The traditional way:

If Len (mylist):  # do something with my listelse:  # The list is empty

Because an empty list itself is equivalent to False, you can directly:

If mylist:  # do something with my listelse:  # The list is empty

2. Get the index while traversing the list

The traditional way:

i = 0for 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

Sorting by an attribute in the list containing an element is a common operation. 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 ' for ' in '    (14, 78, 42)]

The traditional way 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, more readable approach is to use the operator module in the Python standard library:

From operator import Attrgetter to element in sorted (persons, Key=attrgetter (' Age ')):  print "Age:", element.age

The Attrgetter method overrides the Read property value as a parameter passed to the sorted method. The operator module also includes the Itemgetter and Methodcaller methods, which act as literal meanings.

4. Grouping elements in Dictionary

Similar to the above, create Persons first:

class Person (object):  def __init__ (self, age): Self.age = Age persons = [person ' age ' for ' age ' in    (78, 14, 78, 42, 1 4)]

If we are to group by age now, one way is to use the in operator:

Persons_by_age = {} for persons: Age  = Person.age if age in  persons_by_age:    Persons_by_age[age].app End (person)  else:    persons_by_age[age] = [person] assert Len (persons_by_age[78]) = = 2

By comparison, the way to use 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 create a corresponding value for each nonexistent key using the accepted parameters, here we pass the list, so it will create a value for the list type for each key.

The example of this article is only the program framework, and the specific function needs to be perfected by the reader according to its own application environment. I hope that the examples described in this article will help you learn python.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.