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:
- The
- 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
- 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