一、认知
列表的定义:列表 由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字 0~9 或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有任何关系。在 Python 中,用方括号( [ ] )来表示列表,并用逗号来分隔其中的元素。
列表的创建:
列表(打了激素的数组):可以存储任意数据类型
>>> list = [1,1.2,True,'hello']
>>> print(list,type(list))
([1, 1.2, True, 'hello'], <type 'list'>)
列表里面也是可以嵌套列表的
>>> list2 = [1,2,3,[1,1.2,True,'hello']]
>>> print(list2,type(list2))
([1, 2, 3, [1, 1.2, True, 'hello']], <type 'list'>)
二、列表的特性
1.索引
正向索引
>>> service = ['http','ftp','ssh']
>>> print(service[0])
http
反向索引
>>> service = ['http','ftp','ssh']
>>> print(service[-1])
ssh
2.切片
>>> service = ['http','ftp','ssh']
>>> print(service[::-1]) #列表的翻转
['ssh', 'ftp', 'http']
>>> print(service[1:]) #打印除了第一个元素之外的其他元素
['ftp', 'ssh']
>>> print(service[:-1]) #打印除了最后一个之外的其他元素
['http', 'ftp']
3.重复
>>> service = ['http','ftp','ssh']
>>> print(service * 3)
['http', 'ftp', 'ssh', 'http', 'ftp', 'ssh', 'http', 'ftp', 'ssh']
4.连接
>>> service1 = ['mysql','firewalld']
>>> service = ['http','ftp','ssh']
>>> print(service + service1)
['http', 'ftp', 'ssh', 'mysql', 'firewalld']
5.成员操作符
>>> service = ['http','ftp','ssh']
>>> print('firewalld' in service)
False
>>> print('ftp' in service)
True
>>> print('mysql' not in service)
True
6.for 循环遍历
>>> print('服务显示'.center(50,'*'))
*******************服务显示*******************
service = ['http','ftp','ssh']
for s in service:
print(s,end='')
练习:
假定有下面这样的列表:
names = [‘fentiao’, ‘fendai’, ‘fensi’, ‘apple’]
输出结果为:‘I have fentiao, fendai, fensi and apple.’
方法一:
names = ['fentiao','fendai','fensi','apple']
print('I have ' + names[0] + ',' + names[1] + ',' + names[2] + ' and ' + names[-1] + '.')
方法二:
names = ['fentiao','fendai','fensi','apple']
print('I have ' + ','.join(names[:-1]) + ' and ' + names[-1] + '.')
题目:输入某年某月某日(yyyy-MM-dd),判断这一天是这一年的第几天?
cal = input('请输入日期-yyyy-MM-dd:')
date = cal.split('-')
year = int(date[0])
month = int(date[1])
day = int(date[2])
arr = [0,31,28,31,30,31,30,31,31,30,31,30,31]
num = 0
if ((year % 4 ==0) and (year %100 !=0) or (year % 400 ==0)):
arr[2] = 29
for i in range(1,len(arr)):
if month > i:
num += arr[i]
else:
num += day
break
print('天数:',num)
三、列表的常用方法
1.列表元素的增加
append()
: 追加;追加一个元素到列表中
service = ['http','ftp','ssh']
service.append('firewalld')
print(service)
测试:
['http', 'ftp', 'ssh', 'firewalld']
extend()
: 拉伸;追加多个元素到列表中
service = ['http','ftp','ssh']
service.extend(['mysql','nfs'])
print(service)
测试:
['http', 'ftp', 'ssh', 'mysql', 'nfs']
insert()
: 在指定索引位置插入数据
service = ['http','ftp','ssh']
service.insert(1,'https')
print(service)
测试:
['http', 'https', 'ftp', 'ssh']
2.列表元素的删除
01.使用方法pop( )删除
有时候,你要将元素从列表中删除,并接着使用它的值;在 Web 应用程序中,你可能要将用户从活跃成员列表中删除,并将其加入到非活跃成员列表中。
方法 pop( ) 可删除列表末尾的元素,并让你能够接着使用它。术语弹出 ( pop )源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。
>>> service = ['ftp','http','ftp','ssh']
>>> service.pop()
'ssh'
>>> service
['ftp', 'http', 'ftp']
>>> a = service.pop()
>>> service
['ftp', 'http']
>>> a
'ftp'
>>> service.pop(0) #可以使用 pop() 来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。
'ftp'
>>> service
['http']
>>> service.pop()
'http'
>>> service
[]
>>> service.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop from empty list
02.使用 del 语句删除元素
如果知道要删除的元素在列表中的位置,可使用 del 语句。(从内存中删除一个数据)
使用 del 可删除任何位置处的列表元素,条件是知道其索引。
判断标准: 如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用 del 语句;如果你要在删除元
素后还能继续使用它,就使用方法 pop() 。
03.remove( )根据值删除元素
>>> service = ['ftp','http','ftp','ssh']
>>> a = 'ftp'
>>> service.remove(a)
>>> service
['http', 'ftp', 'ssh']
>>> print("\nA " + a.title() + " is too important for me.")
A Ftp is too important for me.
注意:
使用 remove() 从列表中删除元素时,也可接着使用它的值。
方法 remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
3.列表元素的查看
count()
查看元素在列表中出现的次数
>>> service = ['ftp','http','ftp','ssh','ssh','mysql','ssh']
>>> print(service.count('ftp'))
2
index()
查看指定元素的索引值(可以指定索引范围)
>>> service = ['ftp','http','ftp','ssh','ssh','mysql','ssh']
>>> print(service.index('ssh'))
3
>>> print(service.index('ssh',0,5))
3
4.组织列表:列表元素的排序
01.使用方法 sort() 对列表进行永久性排序
排序:按照Ascii码进行排序的
对字符串排序 不区分大小写
>>> phones = ['Tom','alice','bob','Borry']
>>> phones.sort()
>>> print(phones)
['Borry', 'Tom', 'alice', 'bob']
>>> phones.sort(key=str.lower) #全部转换为小写进行排序
>>> print(phones)
['alice', 'bob', 'Borry', 'Tom']
>>> phones.sort(key=str.upper) #全部转换为大写进行排序
>>> print(phones)
['alice', 'bob', 'Borry', 'Tom']
还可以按与字母顺序相反的顺序排列列表元素,为此,只需向 sort() 方法传递参数 reverse=True 。
>>> service = ['ftp','http','ftp','ssh']
>>> service.sort(reverse=True)
>>> print(service)
['ssh', 'http', 'ftp', 'ftp']
无序排列方法
import random
li = list(range(10)) #转换为列表
print(li)
random.shuffle(li) #使用函数转换为无序排列
print(li)
测试:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 4, 2, 6, 9, 1, 5, 8, 3, 7]
02.使用函数 sorted() 对列表进行临时排序
要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数 sorted() 。函数 sorted() 让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
测试:
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
5.列表元素的修改
通过索引值,重新赋值
>>> service = ['ftp','http','ftp','ssh','ssh','mysql','ssh']
>>> service[0] = 'samba'
>>> print(service)
['samba', 'http', 'ftp', 'ssh', 'ssh', 'mysql', 'ssh']
通过切片赋值
>>> service = ['ftp','http','ftp','ssh','ssh','mysql','ssh']
>>> service[:2] = ['mysql','nginx']
>>> print(service)
['mysql', 'nginx', 'ftp', 'ssh', 'ssh', 'mysql', 'ssh']
练习:
题目:输入三个整数x,y,z,请把这三个数由小到大输出
arr_str = input('请输入三个数字:\n')
arr = arr_str.split()
print(arr)
for i in range(len(arr)):
arr[i] = int(arr[i])
arr.sort()
print('输入的结果是:\n' + str(arr))
测试:
请输入三个数字:
5 3 4
['5', '3', '4']
输入的结果是:
[3, 4, 5]