016,序列

016,序列

 列表、元组和字符串的共同点:
-都可以通过索引得到每一个元素
-默认索引值总是从0开始
-可以通过分片的方法得到一个范围内的元素集合
-有很多共同的操作符(重复操作符,拼接操作符,成员关系操作符) 
 
列表和元组和字符串统称为序列。常见内置方法:
list() 把一个可迭代对象转换为列表
 
>>> help(list)
Help on class list in module builtins:
 
class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 list有两个参数,一个是建立可以空列表,一个是迭代器(iterable),所谓迭代,是重复反馈过程的活动,其目的通常是为了接近或达到所需的目标或结果。每一次过程的重复我们叫迭代,每一次迭代的结果都会用作下一次迭代的初始值。 
>>> a = list()
>>> a
[]
>>> b = 'i love fishc.com'
>>> b = list(b)
>>> b
['i', ' ', 'l', 'o', 'v', 'e', ' ', 'f', 'i', 's', 'h', 'c', '.', 'c', 'o', 'm']
>>> 
 >>> c = (1,1,2,3,5,8,13,21,34)                #把元组转化为列表
>>> c = list(c)
>>> c
[1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> 
 
tuple([iterable]) 把一个可迭代对象转换为元组 
>>> help(tuple)
Help on class tuple in module builtins:
 
class tuple(object)
 |  tuple() -> empty tuple
 |  tuple(iterable) -> tuple initialized from iterable's items
 |  
 |  If the argument is a tuple, the return value is the same object.
 
str(obj)  把obj对象转换为字符串 
>>> help(str)
Help on class str in module builtins:
 
class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 
len(sub) 返回参数sub的长度
max()返回序列或者参数中的最大值
min()返回序列或者参数中的最小值(每个元素必须类型一致)

sum(iterable[,start = 0])返回序列iterable和可选参数start的总和
 (类型需保持一致)
>>> help(sum)
Help on built-in function sum in module builtins:
 
sum(...)
    Return the sum of an iterable of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).  When the iterable is
    empty, return start.
 如:
>>> tuple2 = (3.1,2.3,3.4)
>>> sum(tuple2)
8.8
>>> 
 >>> sum(tuple2,3.6)
12.4
>>> 
 
 如果不是数据类型如字符串:
>>> chars
'1234567890'
>>> sum(chars)
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    sum(chars)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 
 
 sorted()返回一个排序的列表,默认从小到大,类似list.sort()
reversed()类似list.reverse() (逆行)
>>> reversed(tuple2)
<reversed object at 0x0224AB90>            #这不是报错,这里返回的是一个迭代器对象
>>>
 >>> list(reversed(tuple2)) 通过list间接转化为列表。
[3.4, 2.3, 3.1]
>>> 

enumerate() 枚举。生成由每个元素的index(索引值)和item
(元素)组成的元组
 如:
>>> numbers
[1, 18, 13, 0, -98, 34, 54, 76, 32]
>>> enumerate(numbers)
<enumerate object at 0x0224ECD8>             #返回一个对象
>>> list(enumerate(numbers))
[(0, 1), (1, 18), (2, 13), (3, 0), (4, -98), (5, 34), (6, 54), (7, 76), (8, 32)]                #(索引值,元素)
>>> 
 
zip()返回由各个参数的序列组成的元组 (打包)(木桶原理)
>>> a = [1,2,3,4,5,6,7,8]
>>> b = [4,5,6,7,8]
>>> zip(a,b)
<zip object at 0x0225E418>
>>> list(zip(a,b))
[(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]
>>> 
 

测试题:
   
0. 我们根据列表、元祖和字符串的共同特点,把它们三统称为什么?
答:序列
序列,因为他们有以下共同点:    
1)都可以通过索引得到每一个元素
2)默认索引值总是从0开始(当然灵活的Python还支持负数索引)
3)可以通过分片的方法得到一个范围内的元素的集合
4)有很多共同的操作符(重复操作符、拼接操作符、成员关系操作符)

1. 请问分别使用什么BIF,可以把一个可迭代对象转换为列表、元祖和字符串?
答:list()    tuple()    str()
list([iterable]) 把可迭代对象转换为列表
  
tuple([iterable]) 把可迭代对象转换为元祖
  
str(obj)  把对象转换为字符串

2. 你还能复述出“迭代”的概念吗?
答:
所谓迭代,是重复反馈过程的活动
所谓迭代,是重复反馈过程的活动,其目的通常是为了接近并到达所需的目标或结果。每一次对过程的重复被称为一次“迭代”,而每一次迭代得到的结果会被用来作为下一次迭代的初始值。

3. 你认为调用 max('I love FishC.com') 会返回什么值?为什么?
答: 
 ‘v’   返回字符的ASCII码的最大值
会返回:'v',因为字符串在计算机中是以ASCII码的形式存储(ASCII对照表:bbs.fishc.com/thread-41199-1-1.html),参数中ASCII码值最大的是'v'对应的118

4. 恢复下图被划掉的代码:

答: 
 
name = input('')
score = [['',85],['',80],['',65],['',95],['',90]]
for each in score:
    if name == each[0]:
        print(name + '',each[1])
        break
if name != each[0]:
    print('')
 
  1. name = input('请输入待查找的用户名:')
  2. score = [['迷途', 85], ['黑夜', 80], ['小布丁', 65], ['福禄娃娃', 95], ['怡静', 90]]
  3. IsFind = False
  4. for each in score:
  5.     if name in each:
  6.         print(name + '的得分是:', each[1])
  7.         IsFind = True
  8.         break
  9.     
  10. if IsFind == False:
  11.     print('查找的数据不存在!')
  12.  
动动手:
   
0. 猜想一下 min() 这个BIF的实现过程 
答: 
a = [1,2,4,6,8,123]                    #必须从小到大排好序。
min = a[1] # min 
for each in a:
    if each < min:
        min = each
        print(min) 
 
  1. def min(x):
  2.     least = x[0]
  3.     for each in x:
  4.         if each < least:
  5.             least = each
  6.     return least
  7. print(min('123456789'))
复制代码
注:关于函数的定义和使用在下一讲的课程中讲解,目前只需要理解该BIF实现的原理即可。
 
 1. 视频中我们说 sum() 这个BIF有个缺陷,就是如果参数里有字符串类型的话就会报错,请写出一个新的实现过程,自动“无视”参数里的字符串并返回正确的计算结果
答:不会。 
  1. def sum(x):
  2.     result = 0
  3.     
  4.     for each in x:
  5.         if (type(each) == int) or (type(each) == float):
  6.             result += each
  7.         else:
  8.             continue
  9.     return result
  10. print(sum([1, 2.1, 2.3, 'a', '1', True]))
posted @ 2014-02-28 17:35  小丑戌  阅读(652)  评论(0编辑  收藏  举报