Python CookBook2 Fourth Python tips-return If an element exists in the list && create a list of lists without sharing references

Source: Internet
Author: User

If an element exists in the list, the returned

Task:

You have a list L, there is an index number I, if I is a valid index, return l[i], if not, return the default value V

Solution:

  1. The
  2. list supports bidirectional indexing, so I can be negative
     >>> def  list_get (L,i,v=none):  if -len (l) <= i < Len (l):  return   L[i]  else  :  return   v  >>> list_get ([1,2,3,4,5,6],3 4 

     

  3. Exception mechanism
    def list2_get (l,i,v=None):    try:        return  l[i]     except indexerror:         return ' ERror '    >>> List2_get ([1,2,3,4,5,6],7)'ERror'

Create a list of lists without sharing references

Task:

Create a multi-dimensional list to avoid implicit reference sharing at the same time.

Solution:

Use list derivation to create a 5 x 10 matrix of all 0:

 for inch  for  in range (ten)>>> test_list[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Python CookBook2 Fourth Python tips-return If an element exists in the list && create a list of lists without sharing references

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.