Lecture 6 - Objects
1. Tuple
Compound data types:
- Tuples
- Lists
- Dictionaries
Tuple:
- t1 = (1, ‘two’, 3)
print(t1)
- t1 = (1, ‘two’, 3)
example:
## divisors def 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 divisors divisors = findDivisors(20, 100) total = 0 for d in divisors: total += d print(total)`
2. Lists
BIG DIFFERENCE WITH TUPLE:
- Lists are mutable!! While tuple, int, float, str are immutable. So lists can be modified aMer they are created!
example:
## universities
Techs = ['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)
3. OPERATIONS ON LISTS
Append:
- Techs.append(Ivys)
- Then Techs returns [‘MIT’, ‘Cal Tech’, ‘RPI’, [‘Harvard’, ‘Yale’, ‘Brown’]]
- side effect: Creates a new list
- so we can use: flat = Techs + Ivys
- Then flat returns [‘MIT’, ‘Cal Tech’, ‘RPI’,’Harvard’, ‘Yale’, ‘Brown’]
Cloning:
- Avoid mutatating a list over which one is iterating
example:
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 counterWhen 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
4. FUNCTIONS AS OBJECTS
concept: Functions are first class objects
- They have types
- They can be elements of data structures like lists
- They can appear in expressions
- As part of an assignment statement
- As an argument to a func%on!!
Example:
# applyToEach def 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)]
5. DICTIONARIES
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’