Compound data types:
TuplesLists DictionariesTuple:
t1 = (1, ‘two’, 3) PRint(t1)example:
## divisorsdef findDivisors(n1, n2): """assumes that n1 and n2 are positive ints returns a tuple containing the common divisors of n1 and n2""" divisors = () # the empty tuple for i in range(1, min(n1, n2) + 1): if n1%i == 0 and n2%i == 0: divisors = divisors + (i,) return divisorsdivisors = findDivisors(20, 100)total = 0for d in divisors: total += dprint(total)`BIG DIFFERENCE WITH TUPLE:
Lists are mutable!! While tuple, int, float, str are immutable. So lists can be modified aMer they are created!example:
## universitiesTechs = ['MIT', 'Cal Tech']Ivys = ['Harvard', 'Yale', 'Brown']Univs = [Techs, Ivys]Univs1 = [['MIT', 'Cal Tech'], ['Harvard', 'Yale', 'Brown']]Techs.append('RPI')print('Univs = ')print(Univs)print('')print('Univs1 =')print(Univs1)for e in Univs: print('Univs contains ') print(e) print(' which contains') for u in e: print(' ' + u)Append:
Techs.append(Ivys)Then Techs returns [‘MIT’, ‘Cal Tech’, ‘RPI’, [‘Harvard’, ‘Yale’, ‘Brown’]]side effect: Creates a new listso we can use: flat = Techs + IvysThen flat returns [‘MIT’, ‘Cal Tech’, ‘RPI’,’Harvard’, ‘Yale’, ‘Brown’]Cloning:
Avoid mutatating a list over which one is iteratingexample:
def removeDups(L1, L2): for e1 in L1: if e1 in L2: L1.remove(e1)L1 = [1,2,3,4]L2 = [1,2,5,6]removeDups(L1, L2)Then print(L1) returns [2, 3, 4]
WHY???
Inside for loop, Python keeps track of where it is in list using internal counter
When we mutate a list, we change its length but Python doesn’t update counter
Better is to clone
def removeDupsBetter(L1, L2): L1Start = L1[:] for e1 in L1Start: if e1 in L2: L1.remove(e1) L1 = [1,2,3,4] L2 = [1,2,5,6] removeDupsBetter(L1, L2)- Note that using L1Start = L1 is not sufficient
concept: Functions are first class objects
They have typesThey can be elements of data structures like listsThey can appear in expressions As part of an assignment statementAs an argument to a func%on!!Example:
# applyToEachdef applyToEach(L, f): """assumes L is a list, f a function mutates L by replacing each element, e, of L by f(e)""" for i in range(len(L)): L[i] = f(L[i])L = [1, -2, 3.4]def fact(n): if n == 1: return 1 else: return n*fact(n-1)def fib(n): if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2)applyToEach(L, abs)print(L)applyToEach(L, int)print(L)applyToEach(L, fact)print(L)applyToEach(L, fib)print(L)Map
对可迭代函数’iterable’中的每一个元素应用‘function’方法,将结果作为list返回。
举例: >>> def add100(x):... return x+100... >>> hh = [11,22,33]>>> map(add100,hh)[111, 122, 133]如果给出了额外的可迭代参数,则对每个可迭代参数中的元素‘并行’的应用‘function’。(翻译的不好,这里的关键是‘并行’)
>>> def abc(a, b, c):... return a*10000 + b*100 + c... >>> list1 = [11,22,33]>>> list2 = [44,55,66]>>> list3 = [77,88,99]>>> map(abc,list1,list2,list3)[114477, 225588, 336699]看到并行的效果了吧!在每个list中,取出了下标相同的元素,执行了abc()。
如果’function’给出的是‘None’,自动假定一个‘identity’函数(这个‘identity’不知道怎么解释,看例子吧)
>>> list1 = [11,22,33]>>> map(None,list1)[11, 22, 33]>>> list1 = [11,22,33]>>> list2 = [44,55,66]>>> list3 = [77,88,99]>>> map(None,list1,list2,list3)[(11, 44, 77), (22, 55, 88), (33, 66, 99)]Concept: Dict is generalization of lists, but now indices don’t have to be integers – can be values of any immutable type
Syntax:
monthNumbers = { ‘Jan’:1, ‘Feb’:2, ‘Mar’:3, 1:’Jan’, 2:’Feb’, 3:’Mar’}Keys can be complex
myDict = {(1,2): 'twelve', (1,3): 'thirteen'}myDict[(1,2)]returns ‘twelve’新闻热点
疑难解答