MIT 6.00.1X 计算机科学和PYTHON编程导论-学习笔记(六) 对象


前五节lecture学到的算法:

1.穷举

2.猜测和验证

3.二分法

4.分而治之

简单数据类型:

1.数字型: int float

2.字符串 str

混合数据类型:

1.tuples 元组

2.lists 

 3.dictionaries

       元组:
      定义: ordered sequence of elements (similar to string)
             Elements can be more than just characters
       e.g.  t1 = (1, ’two’ ,3)
            t2 = (t1, ‘four’)
          >>>t2 = ((1, ‘two’, 3), ‘four’)
       Operations on tuples:
1.级联      Print(t1+t2)
               >>>(1, ’two’ ,3, ’four’)
2.检索      (t1+t2)[3]
3.切片      (t1+t2)[2: 5]
               >>>(‘two’,3,’four’)
4.单元素元组表达方法:t3 =(‘five’, )   (这个逗号别忘了)
5.空元组  t4 = ()           
        

e.g.

## 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)

When a tuple has only one element, you must specify it as follows: (elt,). Here is an example shell session that illustrates the difference:

>>> tup1 = (5)
>>> print tup1
5
>>> type(tup1)

>>> tup2 = (5,)
>>> print tup2
(5,)
>>> type(tup2)

>>> x = (2,3)
>>> x[0] = 8
Traceback (most recent call last):
  File "", line 1, in
    x[0] = 8
TypeError: 'tuple' object does not support item assignment
>>>

这个故事告诉我们 tuple 类型数据不接受 element 赋值  字符串str 也是这样的


>>> x =(2,3)
>>> x[0]
2
>>> type(x[0])

>>> x[0:1]
(2,)
>>>

这个故事告诉我们 检索得到的是这个元素自己的类型  而切片得到的是元组,即使看上去这个切片和检索是一样的

列表(list) :

ccc = ['a',1]

单元素列表: ccc = ['a']
列表是可变的(对比元组)

 e.g. ccc = ['a','c',1]

ccc[1] = 2

>>>ccc = ['a',2,1]

.append()    在一个列表的末尾添加另一个列表 

     +           将两个列表中的元素复制,并按顺序放到一个新列表中,原先的两个列表

c = ccc 和c = ccc[:] 的区别:

前一个是: ccc和一个list(列表)绑定了  然后c 也绑定了那个list  所以ccc和c 会随对方的变化产生相同的变化

后一个是 把ccc 绑定的那个列表克隆给了c 也就是又创建了一个新的list 这个list 跟ccc的list 一样

但是之后ccc的列表变了 c的不变  也就是 2个列表是独立的  之后一个怎么变 都不会影响另一个。





class  range ( stop )
class  range ( startstop [step ] )

The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__ special method). If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

A range object will be empty if r[0] does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.

Ranges containing absolute values larger than sys.maxsize are permitted but some features (such as len()) may raise OverflowError.

Range examples:

>>>
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]

Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).

start

The value of the start parameter (or 0 if the parameter was not supplied)

stop

The value of the stop parameter

step

The value of the step parameter (or 1 if the parameter was not supplied)

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the startstop and step values, calculating individual items and subranges as needed).

Range objects implement the collections.abc.Sequence ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (seeSequence Types — list, tuple, range):

>>>
>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18

你可能感兴趣的:(MIT,6.00.1.X,学习笔记)