namelist = [‘well‘,‘tom‘] nl = namelist ##does not copy the list #Instead, assignment makes the two variables point to the one list in memory.
list = [] ## Start as the empty list list.append(‘a‘) ## Use append() to add elements list.append(‘b‘)
list = [‘a‘, ‘b‘, ‘c‘, ‘d‘] print list[1:-1] ## [‘b‘, ‘c‘] list[0:2] = ‘z‘ ## replace [‘a‘, ‘b‘] with [‘z‘] print list ## [‘z‘, ‘c‘, ‘d‘]
for var in list #遍历一个列表 value in collection #测试集合中是否存在一个值
List常用方法:
list.append(elem) #-- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original. list.insert(index, elem) #-- inserts the element at the given index, shifting elements to the right. list.extend(list2) #adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend(). list.index(elem) -- #searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError). list.remove(elem) -- #searches for the first instance of the given element and removes it (throws ValueError if not present) list.sort() -- #sorts the list in place (does not return it). (The sorted() function shown below is preferred.) list.reverse() -- #reverses the list in place (does not return it) list.pop(index) -- #removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def last(a): return a[-1] def sort_last(tuples): # +++your code here+++ return sorted(tuples,key=last)
def linear_merge(list1, list2): # +++your code here+++ # LAB(begin solution) result = [] # Look at the two lists so long as both are non-empty. # Take whichever element [0] is smaller. while len(list1) and len(list2): if list1[0] < list2[0]: result.append(list1.pop(0)) else: result.append(list2.pop(0)) # Now tack on what‘s left result.extend(list1) result.extend(list2) return result
原文:http://blog.csdn.net/tao_sun/article/details/18743599