1.列表定义
列表是由一系列按特定顺序排列的元素组成,他是python当中内置的可变序列。在形式上,列表的所有元素都放在一堆中括号[]里面,两个相邻的元素之间用逗号隔开,在内容上可以将整数、实数、字符串、列表、元组等任何类型的内容放入列表中并且同一个列表中,元素的类型可以不同,因为他们之间没有任何关系。python中的列表是非常灵活的,这一点去其他语言不同。
2.列表的创建
列表中通常情况下只放入一种类型的数据,这样可以提高程序的可读性
使用赋值运算符创建列表

list = [1,1.2,False,True,'westos']  定义列表内的元素依次为整型、浮点型、布尔型、字符串类型
print(list)   打印列表
print(type(list))  查看类型

打印结果
[1, 1.2, False, True, 'westos']
<class 'list'>    list:类型为列表
创建嵌套列表
list = [1,1.2,True,'westos',[1,2,3,4,5]]


ipython中演示效果
print(list)   打印列表
[1, 1.2, True, 'westos', [1, 2, 3, 4, 5]]
In [7]: print (list)                                                            
[1, 1.2, True, 'westos']
In [8]: list = [1,1.2,True,'westos']                                            
In [9]: print (list)                                                            
[1, 1.2, True, 'westos']
In [10]: print (type(list))                                                     
<class 'list'>

3.索引

service = ['http','ssh','ftp']
print(service[0])    打印第一个元素
print(service[-1])   打印倒数第一个元素

打印结果
http
ftp
3.1嵌套列表索引
service = [['http','80'],['ssh','22'],['ftp','21']]
print(service[0][1])
print(service[-1][1])

打印结果
80
21

4.切片

service = ['http','ssh','ftp']
print(service[::-1])  倒排序
print(service[1:])  除了第一个都打印
print(service[:-1])  除了最后一个都打印

打印结果
['ftp', 'ssh', 'http']
['ssh', 'ftp']
['http', 'ssh']

嵌套列表切片
service = [['http','80'],['ssh','22'],['ftp','21']]
print(service[:][1])   打印列表里面的所有元素(列表)并打印第二个元素元素(列表)
print(service[:-1][0])   除了最后一个元素(列表)都打印并且只打印第一个元素(列表)

打印结果
['ssh', '22']
['http', '80']

5.重复

service = ['http','ssh','ftp']
print(service * 3)
打印结果
['http', 'ssh', 'ftp', 'http', 'ssh', 'ftp', 'http', 'ssh', 'ftp']

6.连接

service = ['http','ssh','ftp']
service1 = ['westos','hello']
print(service + service1)
打印结果
['http', 'ssh', 'ftp', 'westos', 'hello']

6.成员操作符

ervice = ['http','ssh','ftp']
service1 = ['westos','hello']
print('http' in service1)   http不在service1里面为假
print('http' in service)   
print('http' not in  service)  (not  in)存在为假
print('http' not in  service1)    不存在为真


打印结果
False
True
False
True

7.for循环遍历

遍历:遍历列表中的所有元素是常用的一种的操作,在遍历的过程中可以完成查询、处理等功能。在生活中如果想去买衣服那就要把所有的服装店都要逛一遍,看是否有喜欢的才会去买,那么逛服装店就是遍历的一个操作。

service = ['http','ssh','ftp']   列表自定义
for se in service:     
    print(se)     se表示获取到列表当中的元素并输出
 打印结果
http
ssh
ftp

8.计算序列的长度、最大值最小值
使用len()函数计算计算序列的长度,即返回序列当中有多少个元素
使用min函数()返回序列当中值最大的元素
使用max()函数返回序列当中值最大的元素

li = [1,2,3,4,5,6,7,8,9]
print('序列li的长度为', len(li))
print('序列'':''li','最大值是',':',max(li))
print('序列'':''li','最小值为'':',min(li))
打印结果
序列li的长度为 9
序列:li 最大值是 : 9
序列:li 最小值为: 1

活学活用(习题)

  1. 假定有下面这样的列表:
    names = [‘fentiao’, ‘fendai’, ‘fensi’, ‘apple’]
    输出结果为:‘I have fentiao, fendai, fensi and apple.’
.join()连接函数
names = ['fentiao', 'fendai', 'fensi', 'apple']
print('I have '  +  ', '.join(names[:-1]) + ' and' + names[-1])
', '表示以逗号和空格连接但除了最后一个
打印结果
I have fentiao, fendai, fensi andapple