Tips for using collection in Python _python

Source: Internet
Author: User

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.

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.