環(huán)境:mac os x
1涌穆、創(chuàng)建簡(jiǎn)單的python列表
先從簡(jiǎn)單的顏色列表入手:
white
black
blue
red
yellow
上面列表,用python能理解的方式來寫:
colors = ["white",
"black",
"blue",
"red",
"yellow"]
為了把人可讀的列表轉(zhuǎn)換成python可讀的列表雀久,需要遵循以下四個(gè)步驟:
1.在數(shù)據(jù)兩邊加引號(hào)宿稀,將各個(gè)顏色名稱轉(zhuǎn)換成字符串。
2.用逗號(hào)將列表項(xiàng)與下一項(xiàng)分隔開赖捌。
3.在列表的倆邊加上開始和結(jié)束中括號(hào)祝沸。
4.使用賦值操作符(=)將這個(gè)列表賦值一個(gè)標(biāo)識(shí)符(以上代碼中的colors)。
$ colors = ["white",
"black",
"blue",
"red",
"yellow"]
列表就像是數(shù)組:在colos中越庇,white是第0項(xiàng)罩锐、black是第1項(xiàng)...
2、訪問列表數(shù)據(jù)
1) 打印列表中所有數(shù)據(jù)
$ print(colors)
$ print(colors)
['white', 'black', 'blue', 'red', 'yellow']
2) 打印列表中單個(gè)數(shù)據(jù)卤唉,使用中括號(hào)偏移量記法訪問列表數(shù)據(jù)
$ print(colors[1])
$ print(colors[1])
black
3) 得到列表中含有多少個(gè)數(shù)據(jù)項(xiàng)
$ print(len(colors))
$ print(len(colors))
5
3涩惑、編輯列表
1) 在列表末尾增加一個(gè)數(shù)據(jù)項(xiàng) append()
$ colors.append("green")
$ colors.append("green")
$ print(len(colors))
6
2) 從列表末尾刪除一個(gè)數(shù)據(jù)項(xiàng) pop()
$ colors.pop()
$ colors.pop()
'green'
$ print(len(colors))
5
3) 在列表末尾增加一個(gè)數(shù)據(jù)項(xiàng)集合 extend()
$ colors.extend(["green","gray"])
$ colors.extend(["green","gray"])
$ print(colors)
['white', 'black', 'blue', 'red', 'yellow', 'green', 'gray']
4) 在列表某個(gè)特定的位置增加一個(gè)數(shù)據(jù)項(xiàng) insert()
$ colors.insert(1,"orange")
$ colors.insert(1,"orange")
$ print(colors)
['white', 'orange', 'black', 'blue', 'red', 'yellow', 'green', 'gray']
5) 在列表刪除一個(gè)特定的數(shù)據(jù)項(xiàng) remove()
$ colors.remove("orange")
$ colors.remove("orange")
$ print(colors)
['white', 'black', 'blue', 'red', 'yellow', 'green', 'gray']
3、處理列表數(shù)據(jù)
1) 迭代列表 for in
for 目標(biāo)標(biāo)識(shí)符 in 列表: //冒號(hào)放在列表名稱后:指示列表處理代碼開始
列表處理代碼
$ for each_color in colors:
print(each_color)
$ for each_color in colors:
print(each_color)
white
black
blue
red
yellow
green
gray
注:使用for循環(huán)是可伸縮的桑驱,適用于任意大小的列表竭恬。
2) 迭代列表 while
$ count = 0
$ while count < len(colors):
print(colors[count])
count = count + 1
count = 0
$ while count < len(colors):
print(colors[count])
count = count + 1
white
black
blue
red
yellow
green
gray
4跛蛋、列表嵌套列表
1) 定義一個(gè)列表,并嵌套列表
$ colors = ["white",
"red",
"black",
["#fff","#ff2600","#000"]]
$ print(colors)
$ colors = ["white","red","black",["#fff","#ff2600","#000"]]
$ print(colors)
['white', 'red', 'black', ['#fff', '#ff2600', '#fff']]
2) 往列表中痊硕,插入添加另一個(gè)列表
$ colors = ["white",
"red",
"black"]
$ colors1 = ["#fff",
"#ff2600",
"#000"]
$ colors.append(colors1)
$ print(colors)
$ colors = ["white","red","black"]
$ colors1 = ["#fff","#ff2600","#000"]
$ colors.append(colors1)
$ print(colors)
['white', 'red', 'black', ['#fff', '#ff2600', '#fff']]
5赊级、復(fù)雜數(shù)據(jù)處理
1) 處理嵌套列表
$ for each_color in colors:
if isinstance(each_color,list):
for nest_color in each_color:
print(nest_color)
else:
print(each_color)
white
red
black
#fff
#ff2600
#fff