Introduction to some advanced methods of using list lists in Python

Source: Internet
Author: User
Determines whether 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

Get an index while traversing a 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

List sort

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 = agepersons = [person ' age ' for ' in '    (14, 78, 42)]

The traditional way is:

def get_sort_key (Element):  return element.agefor 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 attrgetterfor 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.

List parsing

Python has a very interesting function, that is, list parsing, that is:

>>> squares = [x**2 for x in range (1,10)]>>> squares[1, 4, 9, 16, 25, 36, 49, 64, 81]

Crossing not surprised to see this result? This is Python, the pursuit of simple and elegant python!

In its official documentation, there is a description of the meaning of List parsing:

List Comprehensions provide a concise to create lists. Common applications is to make new lists where each element is the result of some operations applied to each member of an Other sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

Do you remember that question in the previous lecture?

Find the positive integers within 100 that can be divisible by 3.

The method we use is:

aliquot = []for N in range (1,100):  if n%3 = = 0:    aliquot.append (n) Print aliquot

All right. Now with the list parsing rewrite, this will be the case:

>>> aliquot = [n for n in range (1,100) if n%3==0]>>> aliquot[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36 , 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

Shook it. Absolute Bull X!

In fact, not only the number of the list, all can do so. Please, after calming the excited heart, look silently at the following code, feeling the charm of the list parsing.

>>> mybag = [' Glass ', ' apple ', ' green leaf ']  #有的前面有空格, some have spaces behind >>> [One.strip () for one in mybag]
  
    #去掉元素前后的空格 [' Glass ', ' apple ', ' green leaf ']
  

Enumerate

This is an interesting built-in function where we can get the number of each element of a list by means of the for I in range (Len list), and then get the element in the way of List[i]. What if I want to get the element number and element at the same time? That's it:

>>> for I in range (Len (week)): ...   . Print week[i]+ ' is ' +str (i)   #注意, I is of type int, if and previous with + connection, must be str type ... Monday is 0sunday is 1friday is 2

Python provides a built-in function enumerate that enables similar functionality

>>> for (I,day) in Enumerate (week): ...   Print day+ ' is ' +str (i) ... Monday is 0sunday-1friday is 2

is an interesting built-in function, mainly to provide a simple and quick method.

This is what the official document says:

Return an Enumerate object. Sequence must is a sequence, an iterator, or some other object which supports iteration. The next () method of the iterator returned by enumerate () returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating through sequence:

By the way to transcribe a few examples, for crossing appreciation, it is best to experiment.

>>> seasons = [' Spring ', ' Summer ', ' Fall ', ' Winter ']>>> list (enumerate (seasons)) [(0, ' Spring '), (1, ' Summer '), (2, ' Fall '), (3, ' Winter ')]>>> list (Enumerate (seasons, Start=1)) [(1, ' Spring '), (2, ' Summer '), (3, ' Fa ll '), (4, ' Winter ')]
  • 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.