PYTHON从入门到实践-第三章
3.1 列表
family = ['casper','zoe']
print(family[0].title()) # 其实中括号[]就是代表‘列表’
print(family[-1].title())
# 动手试一试 3-2
family=['casper','zoe']
print('hey,'+family[0]+'\nit has been two years since we met at the first time\n'+family[-1])
敲黑板,用print()函数时,怎样打印出变量带换行符的,将换行符当做字符串,加引号即可:
message=('Dear all')
print(message +'\n'+'Thank you for your prompt reply')
3.2 修改、添加和删除元素
3.2.1 方法append
family=['casper','zoe']
family.append('hotpot')
family.append('three')
print(family)
敲黑板,遇到两个错误
1、append函数是在列表末尾追加单个参数,而我写了两个;
2、此处的变量已经赋值,新增参数无需再次赋值
3.1.2 方法insert
family=['casper','zoe']
family.insert(1,'hotpot')
print(family)
insert也是在某位置插入单个元素
pop 是删除末端的元素或者指定元素,并且可以将该元素输出的一个函数;
remove是可以删除元素值(而非元素的位置),也可以删除整个变量涵盖的单个值;
动手试一试
# 3-2
family=['casper','zoe']
print('hey,'+family[0]+'\nit has been two years since we met at the first time\n'+family[-1])
# 3-4嘉宾名单
guests=['casper','zoe','hotpot','three']
print('Dear '+guests.title()+',\n I would like to invite you to dinner on Tuesday.')
# 3-5修改嘉宾名单
print(guests[-1].title()+' is unable to make our appointment')
guests[-1]='chenxian'
print('Dear '+guests[-1].title()+',\n I would like to invite you to dinner on Tuesday.')
#3-6添加嘉宾
guests.insert(0,'小张')
guests.insert(3,'障障')
guests.append('障障1')
print('our guests list is '+ guests[0],guests[1],guests[2],guests[3],guests[4],guests[5])
#3-7缩减名单
list1=guests.pop()
print('sorry,'+list1 + ', you are not on my list')
list2=guests.pop()
print('sorry,'+list2 + ', you are not on my list')
list3=guests.pop()
print('sorry,'+list3 + ', you are not on my list')
list4=guests.pop()
print('sorry,'+list4 + ', you are not on my list')
list5=guests.pop()
print('sorry,'+list5 + ', you are not on my list')
print(guests)
敲黑板今天请教大神,大概得出的结论,就是del + 变量 是属于关键字,而pop()等是方法,方法的使用是变量.方法();【】是针对数组的;
组织列表
3.3.1 使用方法sort()对列表永久性删除
name=['casper','zoe','amanda','hotpot','three']
name.sort()
print(name)
name.sort(reverse=False)
print(name)
3.3.2 使用函数sorted对列表进行临时排序
name=['casper','zoe','amanda','hotpot','three']
print('here is the original list')
print(name)
print('\nhere is the sorted list')
print(sorted(name))
print('\nhere is the original list again')
print(name)
print('\nhere is the reversed sorted list')
print(sorted(name,reverse=True))
3.3.3 用方法reverse()倒着打印列表(永久修改列表)
name=['casper','zoe','amanda','hotpot','three']
name.reverse()
print(name)
3.3.4 用函数len()确定列表长度
name=['casper','zoe','amanda','hotpot','three']
print(len(name))
动手试一试
# 3-8 放眼望世界
dreamtour=['japan','rio','canada','america','melbourne']
print(dreamtour)
print(sorted(dreamtour))
print(dreamtour)
print(sorted(dreamtour,reverse=True))
print(dreamtour)
dreamtour.reverse()
print(dreamtour)
dreamtour.reverse()
print(dreamtour)
dreamtour.sort()
print(dreamtour)
dreamtour.sort(reverse=True)
print(dreamtour)
# 3-9 晚餐嘉宾
dreamtour=['japan','rio','canada','america','melbourne']
print(len(dreamtour))