一、列表的创建
#列表的创建
# 数组存储同一数据类型的集合 scores = [56 77 89 ....]
# 列表(打了激素的数组):可以存储任意数据类型数据类型
list = [1,2,3,'hello',True,1.2]
print(list)
print(type(list))
#列表里边也可以套嵌列表
list1 = [1,2,3,['haha',1.2,152,True]]
print(list1,type(list1))
二、列表的特性
1、列表的索引(正反索引)
service = ['http','ftp','ssh']
# 索引
# 正向索引
print(service[0])
# 反向索引
print(service[-1])
2、列表的切片
# 2.列表的切片
s = ['westos',1,1.2,'http','hello']
print(s[::-1]) ##倒序
print(s[1:]) ##显示除了第一个元素以外的其他数(s[0]表示i第一个元素)
print(s[-1]) ##显示最后一个元素
3、列表的重复
# 3.列表的重复
s = ['westos',1,1.2,'http','hello']
print(s*3)
print(s[0]*3)
4、列表的连接
#4.列表的连接
s = ['westos',1,1.2,'http','hello']
s1 = [1,2,3,4,5]
print(s + s1)
5、成员操作符
# 5.成员操作符
s = ['westos',1,1.2,'http','hello']
print('west' in s)
print('westos' in s)
print('3' not in s)
6、for循环
#列表特性之for循环
for i in s:
print(i,end='')
print('')
二、列表的练习
#列表练习
#假定有下面这样的列表:
names = ['fentiao', 'fendai', 'fensi', 'apple']
输出结果为:'I have fentiao, fendai, fensi and apple.'
"""
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、列表元素的添加
##列表元素的添加
s = ['http','htp','ssh']
#追加一个元素
s.append('westos')
print(s)
# extend(): 拉伸 追加多个元素到列表
s.extend(['haha','hello'])
print(s)
#insert() :在指定索引出插入元素
s.insert(1,'xixi')
print(s)
2、列表元素的删除
#列表元素的删除
>>> a = '列表元素的删除'
>>> s = ['http','ssh','westos','hello']
>>>
>>> s.pop() ##默认的删除方式是从右向左依次删除
'hello'
>>> s
['http', 'ssh', 'westos']
>>>
>>> a = s.pop()
>>> a
'westos'
>>>
>>> s
['http', 'ssh']
>>>
>>> s.pop(0) ##删除指定索引的值
'http'
>>>
>>> s
['ssh']
>>>
>>> s.pop()
'ssh'
>>> s
[]
>>> s.pop() ##元素为空无法删除
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop from empty list
>>>
3、在linux系统中删除元素
#remove() :删除列表元素
s = ['http','ssh','westos','hello']
a = s.remove('hello')
print(s)
print(a)
#从内存中删除一个元素
del s[1]
print(s)
4、元素列表的查看
##元素列表的查看
s = ['http','ssh','westos','hello','http','westos']
# 查看元素在列表中出现的次数
print(s.count('http'))
##查看指定元素的索引值(可以指定索引值的范围)
print(s.index('http')) ##指定索引列表元素所在的位置
print(s.index('http',3,6)) ##不是在在3~6这个范围内出现http的索引位置
5、列表元素的排序
#列表元素的排序
s = ['http','ssh','westos','hello','http','westos']
##默认按Ascii码进行排序
s.sort(reverse=True)
print(s)
phone = ['Tom','alive','bob','Borry']
phone.sort(key=str.upper)
print(phone)
import random
li = list(range(100))
print(li) ##按默认的方法从小到大进行排列
random.shuffle(li) ##无序的排列
print(li)
6、列表元素的修改
#列表元素的修改
s = ['http','ssh','westos','hello','http','westos']
#通过索引值 重新赋值
s[0] = 'samba'
print(s)
##通过切片赋值
print(s[:2])
s[:2] = ['haha','xixi','lftp']
print(s)
题目:输入三个数判断这三个的大小