3-1姓名:
names=['lmd','ksb','kq','lrp']
for name in names:
print(name)
執行結果:
3-2問候語:
names=['lmd','ksb','kq','lrp']
for name in names:
print(name.title()+" Hi!")
執行結果:
3-3自己的列表:
ways=['motorcycle','bicycle','walk']
print('I like red '+ways[0])
print('I want to ride a '+ways[1])
print('I would like to '+ways[-1])
執行結果:
3-4嘉賓名稱:
people=[]
people.append('ksb')
people.append('lmd')
people.append('kq')
people.append('lrp')
for person in people:
print(person+', please come to have dinner')
執行結果:
3-5修改嘉賓名單:
people=[]
people.append('ksb')
people.append('lmd')
people.append('kq')
people.append('lrp')
for person in people:
print(person+', please come to have dinner')
print("\nksb can't come to the dinner\n")
for i in range(0,len(people)):
if(people[i]=='ksb'):
people[i]='zzy'
print(people[i]+', please come to have dinner')
運行結果:
3-6添加嘉賓:
people=[]
people.append('ksb')
people.append('lmd')
people.append('kq')
people.append('lrp')
for person in people:
print(person+', please come to have dinner')
print("\nksb can't come to the dinner\n")
for i in range(0,len(people)):
if(people[i]=='ksb'):
people[i]='zzy'
print(people[i]+', please come to have dinner')
print("I have a bigger table")
people.insert(0,'llq')
people.insert(3,'hzp')
people.insert(len(people),'hyk')
print(people)
運行結果:
3-7修改名單:
print('I can only invite 2 person to my dinner') while len(people)>2: print(people[-1]+", I am so sorry that you can't come to my dinner") people.pop() for x in people: print(x+', you are still invited') del people[0] del people[0] print(people)
運行結果:
3-8放眼世界:
places=['china','america','russia','japan','france']
print(places)
print(sorted(places))
print(places)
print(sorted(places,reverse=True))
print(places)
places.reverse()
print(places)
places.reverse()
print(places)
places.sort()
print(places)
places.sort(reverse=True)
print(places)
運行結果:
3-9晚餐嘉賓:
print('\nI have invited '+str(len(people))+' people')
運行結果:
3-10嘗試使用各個函數:
#列表(即數組)
arr=['blue',"red",'yellow']#單引號和雙引號作用一樣
print(arr[0])
print(arr[1])
print(arr[-1]) #訪問最後一個元素
arr.append('black'); print(arr)
arr.insert(1,'orange'); print(arr)
del arr[1]; print(arr)
tmp=arr.pop(1);#可以pop出任意位置的元素,沒指定就默認最後一個
print(arr); print(tmp)
arr.remove('yellow')#按值刪除
print(arr)
print("*******************************")
#排序
arr.append("red")
arr.append('yellow')
print(arr)
arr.sort()#順序排
print(arr)
arr=["asf","jic","kisnf","jsafw"]
#永久性排序
arr.sort(reverse=True)#倒序排
print(arr)
#暫時排序
arr=['f','a','c','v','w']
print(sorted(arr,reverse=True))#暫時倒序排
print(arr)
arr.reverse()#倒序
print(arr)
print("length is "+str(len(arr)))
#遍歷列表
for item in arr:
print(item,end=",")
print("\n")
運行結果:
3-11有意引發錯誤:
arr=['aaa','jij','vac']
print(arr[3])
運行結果:
改正:
arr=['aaa','jij','vac']
print(arr[2])
運行結果: