Some suggestions on the Python collection

Source: Internet
Author: User

1. Check if the list is empty

There is no need to call the Len method to detect if a list is empty, because an empty list evaluates to False.

if Len (mylist):     # Do something with my list Else :     # The list is empty

You can use the following method instead:

if mylist:     # Do something with my list Else :     # The list is empty

2. Get the index value of an element at the same time as the iteration list

Sometimes you need to iterate over a list and get the index value for each element. The usual practice is to:

i = 0 for in mylist:    # does something with I and element    i + = 1

A better approach would be to:

 for inch Enumerate (mylist):     # Do something with I and element    Pass

3. List sorting

Create a persons list:

class Person (object):     def __init__ (self, Age):         = for in (14, 78, 42)]

If we want to sort the list by age, we can do this:

def Get_sort_key (Element):     return Element.age  for  in sorted (persons, key=Get_sort_key):    print"age:" , Element.age

We define a function that returns the attributes that are the sort criteria. and pass this function as a parameter to the sorted function. Because this sort is common, the Python standard library already contains such a function.

 from Import Attrgetter # Attrgetter is a high-order function that can return a function  for  in sorted (persons, Key=attrgetter ('age')):    Print " Age : ", Element.age

This makes the code easier to read. When you see the Attrgetter function you will know that it is used to get a property. There are also Itemgetter and Methodcaller methods in the operator module, and I believe you can see their role at a glance.

Some suggestions on the Python collection

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.