# 旭 2018-11-14
#訪問列表元素
bicycles=['trek','cannondale','redline','specialized']
print(bicycles[0])
#修改、添加、刪除元素
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
# motorcycles[0]='ducati' # 修改
# print(motorcycles)
# motorcycles.append('ducati') # 追加
# print(motorcycles)
# motorcycles.insert(1,'ducati') # 插入
# print(motorcycles)
# del motorcycles[0] # del語句刪除元素(要知道刪除元素在列表中的位置)
# print(motorcycles)
# popped_motorcycle=motorcycles.pop() # 刪除尾末元素
# print(motorcycles)
# print(popped_motorcycle)
# motorcycles.pop(1) # 刪除列表中任何位置處的元素
# print(motorcycles)
motorcycles.remove('yamaha') # 根據(jù)值刪除元素
print(motorcycles)
#組織列表
cars=['bmw','audi','toyota','subaru']
# cars.sort() # 使用sort()對列表進行永久排序
# print(cars)
# cars.sort(reverse=True) # 傳參reverse=True,倒序排列
# print(cars)
# print(sorted(cars)) # 使用sorted()對列表進行臨時排序
# print(cars)
# cars.reverse() # 倒著打印列表
# print(cars)
len(cars) # 獲取列表長度
#操作列表
magicians=['alice','david','carolina']
for magician in magicians: # 循環(huán)打印列表
? ? print(magician)
print(magician)? ? ? ? ? ? # 變量magician在最后一次變?yōu)榱薱arolina
for value in range(1,5):? # range()方法創(chuàng)建數(shù)字列表 注:從1開始,到5停止,不包括5
? ? print(value)
even_numbers=list(range(2,11,2)) # range()方法從2開始數(shù),不斷+2,直到達到或者超過11
print(even_numbers)
squares=[value**3 for value in range(0,10)] # 列表解析 生成0-9的立方組成的列表
print(squares)
players=['charles','martina','michael','florence','eli']
print(players[0:3]) # 切片 處理列表中的部分元素 注:從起始索引開始至第二個索引前面的元素結(jié)束
print(players[:3])? # 注:若第一個索引沒有,則從列表起始索引開始切片 若第二個索引沒有,則到列表最后元素索切片結(jié)束
print(players[-3:]) # 若第一個索引為負數(shù),則取列表末尾的元素
print(players[:-3]) # 若第二個索引為負數(shù),則取到列表末尾對應(yīng)倒數(shù)的元素
print(players[-4:-1]) # 從倒數(shù)第四個開始取,取到倒數(shù)第一個結(jié)束 若區(qū)間內(nèi)無元素 則該切片為[]
for player in players[:3]: # 遍歷切片
? ? print(player)
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:] # 復制列表 注:my_foods=friend_foods 這種做法行不通 這樣做實際上得到的還是同一張表
print(friend_foods)
# 元組 元組內(nèi)包含的元素都是不可變的,是不可變的列表
dimensions=(200,50)
# dimensions[0]=100 # 這種寫法程序會報錯
print(dimensions)
dimensions=(100,100) # 雖然不能修改元組中的元素,但是可以給存儲元組的變量賦值來重新定義整個元組
print(dimensions)