文章目錄
- 一、Python程式結構
- 1.if條件
- 2.回圈
- while回圈
- for回圈
- 3.案例-王者榮耀純文本分析
- 二、函式的介紹和基本使用
- 三、串列
- 1.創建串列
- 2.洗掉元素
- 3.添加元素
各位看官朋友,最近“GEEK+”原創·博主大賽TOP 50榜單投票,各位有票的捧個票場,沒票的捧個人場,點擊https://tp.wjx.top/jq/91687657.aspx,投給第3個cutercorley,如下:
投出您最寶貴的一票,您的支持與鼓勵是我繼續創作、不斷努力的動力,我將繼續為大家貢獻原創文章、為您排憂解難,
一、Python程式結構
Python中,有3種常見的程式結構:
- Sequence順序
從上向下依次執行, - Condition條件
滿足某個條件則執行, - Loop回圈
重復執行某個動作,
1.if條件
判斷某個變數是否滿足某個條件時如下:
possibility_to_rain = 0.7
print(possibility_to_rain > 0.8)
print(possibility_to_rain > 0.3)
possibility_to_rain = 1
print(possibility_to_rain > 0.8)
print(possibility_to_rain > 0.3)
輸出:
False
True
True
True
如需本節同步
ipynb檔案,可以直接點擊加QQ群963624318 在群檔案夾商業資料分析從入門到入職中下載即可,
但是如果想在變數滿足某個條件時需要執行某個動作,則需要if條件判斷陳述句,如下:
possibility_to_rain = 0.7
if possibility_to_rain > 0.8:
print("Do take your umberalla with you.") ## 這個地方標準格式是四個空格的縮進
elif possibility_to_rain > 0.3:
print("Take your umberalla just in case. hahaha")
else:
print("Enjoy the sunshine!")
print('hello')
輸出:
Take your umberalla just in case. hahaha
這段代碼的意思是:
如果possibility_to_rain > 0.8為True,則執行print("Do take your umberalla with you."),如果不滿足前述條件,但滿足possibility_to_rain > 0.3,則執行print("Take your umberalla just in case. hahaha"),否則執行print("Enjoy the sunshine!");
if陳述句執行完后,再執行后面的陳述句,如print('hello');
需要注意縮進,if、elif、else陳述句后面的陳述句都應該縮進4格并保持對齊,即通過縮進控制代碼塊和代碼結構,而不像其他語言使用{}來控制代碼結構,如下:

前面也看到,出現了很多以#開頭的代碼和文字性說明,代碼顏色也是和其他代碼有所區別的,這就是Python中的單行注釋,注釋后的代碼不會被執行,而只能起到說明作用,這段代碼中這個地方標準格式是四個空格的縮進被#注釋,這一行前面的代碼能正常執行,#后的文字不會執行、也不會報錯、作為解釋性陳述句,
除了對數值進行判斷,還能對字串進行判斷:
card_type = "debit"
account_type = "checking"
if card_type == "debit":
if account_type == "checking":
print("Checkings selectd.")
else:
print("Savings selected.")
else:
print("Credit card.")
輸出:
Take your umberalla just in case. hahaha
hello
可以看到,使用到了條件判斷的嵌套,
2.回圈
while回圈
之前要是需要執行重復操作,可能如下:
count =1
print(count)
count+=1
print(count)
count+=1
print(count)
count+=1
print(count)
count+=1
print(count)
count+=1
print(count)
count+=1
print(count)
count+=1
print(count)
count+=1
print(count)
count+=1
print(count)
輸出:
1
2
3
4
5
6
7
8
9
10
顯然,代碼很冗長,此時就可以使用回圈進行優化,
使用while回圈如下:
count = 1
while count <= 10:
print(count)
count += 1
執行效果與前面相同;
需要注意,回圈一般要有停止的條件,當滿足count <= 10時回圈會一直執行,直到count = 11時就會不符合、從而退出回圈;
如果沒有停止條件,則可能陷入死回圈、消耗記憶體,
再如:
cnt = 1
while True:
print("cnt = %d" % cnt)
ch = input('Do you want to continue? [y:n]: ')
if ch == 'y':
cnt += 1
else:
break
輸出如下:

可以看到,雖然回圈條件為True,是恒成立的,但是回圈內部進行了條件判斷,輸入的是y就會一直回圈,輸入其他則執行break退出回圈;
但是需要注意,這里只有嚴格地輸入y才能繼續回圈,但是輸入yes都會退出回圈,所以要想進一步控制運行邏輯、還需要對代碼進行完善,
在Python中,else也可以與while回圈結合使用,如果回圈不是因呼叫break而結束的,將執行else中的陳述句,這可以用于判斷回圈是不是完全執行,例如前面第1個回圈的例子是不是運行了10次,
如下:
count = 1
while count < 11:
print(count)
count = count + 1
else:
print('Counting complete.')
print()
count = 1
while count < 11:
print(count)
count = count + 1
if count == 8:
break
else:
print('Counting complete.')
輸出:
1
2
3
4
5
6
7
8
9
10
Counting complete.
1
2
3
4
5
6
7
可以看到:
第一個回圈并沒有因為break而停止回圈,因此在執行完回圈陳述句后執行了else陳述句;
第二個回圈因為count為8時滿足if條件而退出回圈、并未將回圈執行完畢,因此未執行else陳述句,
再如:
count=0
while count < 11:
print("while count:",count)
count = count + 1
if count == 11:
break
else:
print("else:",count)
輸出:
while count: 0
while count: 1
while count: 2
while count: 3
while count: 4
while count: 5
while count: 6
while count: 7
while count: 8
while count: 9
while count: 10
顯然,此時因為執行最后一次回圈時滿足if條件而執行了break陳述句,因此并未執行else陳述句塊,
for回圈
經常與for回圈同時出現的還有range,range(self, /, *args, **kwargs)函式有以下兩種常見的用法:
range(stop) -> range object
range(start, stop[, step]) -> range object
該函式回傳一個物件,該物件以step為步長生成從start(包含)到stop(排除)的整數序列,例如range(i, j)產生i,i+1,i+2,…,j-1的序列,
輸入:
for i in range(10):
print(i)
輸出:
0
1
2
3
4
5
6
7
8
9
再如:
for i in range(4,10):
print(i)
print()
for i in range(4,10,2):
print(i)
print()
for i in range(5):
print('Corley')
print()
for i in range(5):
print('Corley'[i])
輸出:
4
5
6
7
8
9
4
6
8
Corley
Corley
Corley
Corley
Corley
C
o
r
l
e
可以看到,for回圈內也可以執行與i無關的操作;
還可以用來遍歷字串,
for回圈中也可以使用break陳述句來終止回圈,如下:
for i in range(10):
print(i)
if i == 5:
break
輸出:
0
1
2
3
4
5
再如:
result = 0
for num in range(1,100):
if num % 2 == 0:
result = result + num
print(result)
輸出:
2450
上面的例子實作了計算從1到100(不包括)的所有偶數的和,
3.案例-王者榮耀純文本分析
目標是從以下文本提取出所有的英雄資訊鏈接、頭像圖片鏈接、英雄名稱,如herodetail/194.shtml、http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg和蘇烈:
<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt="蘇烈">蘇烈</a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt="百里玄策">百里玄策</a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt="百里守約">百里守約</a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt="鎧">鎧</a></li></ul>
我們可以先找出一個英雄的資訊,即使用下標進行字串切分,找下標時使用find()方法,
例如,對于鏈接http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg,如果找到第一個h字母和最后一個g字母的下標,就可以通過切分將該鏈接提取出來,
先讀入字串,如下:
page_hero = '''<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt="蘇烈">蘇烈</a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt="百里玄策">百里玄策</a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt="百里守約">百里守約</a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt="鎧">鎧</a></li></ul>
'''
此時再通過一步步地獲取與目標相關字符的下標和根據下標切片來獲取目標字串,如獲取圖片鏈接如下:
start_link = page_hero.find('<img src="')
print(start_link)
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_link = page_hero[start_quote+1:end_quote]
print(hero_link)
輸出:
81
http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg
此時再依次獲取英雄名和資訊鏈接如下:
# 第1個英雄
start_link = page_hero.find('<a href="')
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_info1 = page_hero[start_quote+1:end_quote]
print(hero_info1)
start_link = page_hero.find('<img src="', end_quote+1)
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_link1 = page_hero[start_quote+1:end_quote]
print(hero_link1)
end_bracket = page_hero.find('>', end_quote+1)
start_bracket = page_hero.find('<', end_bracket+1)
hero_name1 = page_hero[end_bracket+1:start_bracket]
print(hero_name1)
輸出:
herodetail/194.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg
蘇烈
顯然,已經獲取到第1個英雄的完整資訊,
此時再獲取第2個英雄的資訊,如下:
# 第2個英雄
page_hero = page_hero[start_bracket:]
start_link = page_hero.find('<a href="')
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_info2 = page_hero[start_quote+1:end_quote]
print(hero_info2)
start_link = page_hero.find('<img src="', end_quote+1)
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_link2 = page_hero[start_quote+1:end_quote]
print(hero_link2)
end_bracket = page_hero.find('>', end_quote+1)
start_bracket = page_hero.find('<', end_bracket+1)
hero_name2 = page_hero[end_bracket+1:start_bracket]
print(hero_name2)
輸出:
herodetail/195.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg
百里玄策
需要注意:
第二次切分不需要再在原字串上進行切分、而只要從上次切分的位置開始查找和切分即可,所以page_hero = page_hero[end_quote:]即是將上次切分之后的子字串重新賦值給page_hero作為新字串;
因為各個英雄資訊的字串形式是一樣的,所以可以直接利用查找第一個英雄的方式即可,
查找第3個和第4個英雄也類似如下:
# 第3個英雄
page_hero = page_hero[start_bracket:]
start_link = page_hero.find('<a href="')
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_info3 = page_hero[start_quote+1:end_quote]
print(hero_info3)
start_link = page_hero.find('<img src="', end_quote+1)
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_link3 = page_hero[start_quote+1:end_quote]
print(hero_link3)
end_bracket = page_hero.find('>', end_quote+1)
start_bracket = page_hero.find('<', end_bracket+1)
hero_name3 = page_hero[end_bracket+1:start_bracket]
print(hero_name3)
# 第4個英雄
page_hero = page_hero[start_bracket:]
start_link = page_hero.find('<a href="')
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_info4 = page_hero[start_quote+1:end_quote]
print(hero_info4)
start_link = page_hero.find('<img src="', end_quote+1)
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_link4 = page_hero[start_quote+1:end_quote]
print(hero_link4)
end_bracket = page_hero.find('>', end_quote+1)
start_bracket = page_hero.find('<', end_bracket+1)
hero_name4 = page_hero[end_bracket+1:start_bracket]
print(hero_name4)
輸出:
herodetail/196.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg
百里守約
herodetail/193.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg
鎧
可以看到,找4個英雄的思路都大致如下:
(1)找到第一個出現的<img src= >=>start_link;
(2)找到第一個出現的"=>start_quote;
(3)找到start_quote+1之后那個引號 end_quote;
(4)end_quote+1找到后面的>記作 end_bracket;
(5)end_bracket+1 找到 start_bracket;
(6)拋棄start_bracket之前的所有內容,再根據上面的方法找,
可以看到,3部分代碼也有很大部分相似,因此可以使用回圈來簡化代碼:
# 使用回圈簡化代碼
page_hero = '''<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt="蘇烈">蘇烈</a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt="百里玄策">百里玄策</a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt="百里守約">百里守約</a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt="鎧">鎧</a></li></ul>
'''
for i in range(4):
print('第%d個英雄:' % (i+1))
start_link = page_hero.find('<a href="')
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_info = page_hero[start_quote+1:end_quote]
print(hero_info)
start_link = page_hero.find('<img src="', end_quote+1)
start_quote = page_hero.find('"', start_link)
end_quote = page_hero.find('"', start_quote+1)
hero_link = page_hero[start_quote+1:end_quote]
print(hero_link)
end_bracket = page_hero.find('>', end_quote+1)
start_bracket = page_hero.find('<', end_bracket+1)
hero_name = page_hero[end_bracket+1:start_bracket]
print(hero_name)
page_hero = page_hero[start_bracket:]
輸出:
第1個英雄:
herodetail/194.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg
蘇烈
第2個英雄:
herodetail/195.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg
百里玄策
第3個英雄:
herodetail/196.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg
百里守約
第4個英雄:
herodetail/193.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg
鎧
顯然,代碼精簡很多,
二、函式的介紹和基本使用
函式是一段命名的代碼,并且獨立于所有其他代碼,
函式可以接受任何型別的輸入引數,并回傳任意數量和型別的輸出結果,
簡而言之,函式可以代替大段代碼,在需要使用這些代碼的時候、直接呼叫函式即可,而不再需要重復大段代碼,很大程度上優化了代碼的結構、提高了代碼的可讀性,
定義一個不做任何事的函式如下:
# An empty function that does nothing
def do_nothing():
pass
do_nothing()
type(do_nothing)
輸出:
function
其中,do_nothing()是呼叫函式,即函式名(),
定義一個不帶引數和回傳值的函式如下:
# A function without parameters and returns values
def greeting():
print("Hello Python")
# Call the function
a = greeting()
輸出:
Hello Python
以后需要列印Hello Python的地方,就不用再使用print("Hello Python")陳述句,直接呼叫greeting()即可,
還可以定義帶引數、但是不帶回傳值的函式:
# A function with a parameter that returns nothing
def greeting(name):
print("Hello %s" % name)
# Call the function
greeting('Corley')
輸出:
Hello Corley
此時在呼叫函式時,傳入了引數'Corley',會在函式內部使用,如果引數值變化,在函式內部被使用的變數也會同步變化,導致結果也可能變化,
但是此時:
print(a)
輸出:
None
即回傳為空,這是因為在函式內部并未定義回傳值,
在需要時可以在函式內部定義回傳值,以便用于下一步的運算,
如下:
# A function with a parameter and return a string
def greeting_str(name):
return "Hello again " + name
# Use the function
s = greeting_str("Corley")
print(s)
輸出:
Hello again Corley
像許多編程語言一樣,Python支持位置引數,其值按順序復制到相應的引數中,即可以給函式傳遞多個引數,如下:
# A function with 3 parameters
def menu(wine, entree, dessert):
return "wine:{},entree:{},dessert:{}".format(wine,entree,dessert)
# Get a menu
menu('chardonnay', 'chicken', 'cake')
輸出:
'wine:chardonnay,entree:chicken,dessert:cake'
為了避免位置引數混淆,可以通過引數對應的名稱來指定引數,甚至可以使用與函式中定義不同的順序來指定引數,即關鍵字引數,
如下:
menu(entree='beef', dessert='cake', wine='bordeaux')
輸出:
'wine:bordeaux,entree:beef,dessert:cake'
顯然,此時不按照順序也可以實作傳參,
甚至可以混合使用位置引數和關鍵字引數;
但是需要注意,在輸入任何關鍵字引數之前,必須提供所有位置引數,
如果函式呼叫者未提供任何引數的默認值,則可以為引數設定默認值,
如下:
# default dessert is pudding
def menu(wine, entree, dessert='pudding'):
return "wine:{},entree:{},dessert:{}".format(wine,entree,dessert)
# Call menu without providing dessert
menu('chardonnay', 'chicken')
輸出:
'wine:chardonnay,entree:chicken,dessert:pudding'
可以看到,此時也可以不給dessert引數傳值也能正常運行,因為在定義函式時已經提供了默認值,
當然,也可以給dessert引數傳值,此時就會使用傳遞的值代替默認值,如下:
# Default value will be overwritten if caller provide a value
menu('chardonnay', 'chicken', 'doughnut')
輸出:
'wine:chardonnay,entree:chicken,dessert:doughnut'
在函式中,存在作用域,即變數在函式內外是否有效,
如下:
x = 1
def new_x():
x = 5
print(x)
def old_x():
print(x)
new_x()
old_x()
輸出:
5
1
顯然,第一個函式中的x在函式內部,屬于區域變數,區域變數只能在當前函式內部使用;
第二個函式使用的x函式內部并未定義,因此使用函式外部的x,即全域變數,全域變數可以在函式內部使用,也可以在函式外部使用;
函式內部定義了與全域變數同名的區域變數后,不會改變全域變數的值,
要想在函式內部使用全域變數并進行修改,需要使用global關鍵字進行宣告,
如下:
x = 1
def change_x():
global x
print('before changing inside,', x)
x = 3
print('after changing inside,', x)
print('before changing outside,', x)
change_x()
print('after changing outside,', x)
輸出:
before changing outside, 1
before changing inside, 1
after changing inside, 3
after changing outside, 3
可以看到,此時在函式內部對變數進行修改后,函式外部也發生改變,
此時可以對之前王者榮耀純文本分析案例進一步優化:
# 使用函式實作
def extract_info(current_page):
start_link = current_page.find('<a href="')
start_quote = current_page.find('"', start_link)
end_quote = current_page.find('"', start_quote+1)
hero_info = current_page[start_quote+1:end_quote]
print(hero_info)
start_link = current_page.find('<img src="', end_quote+1)
start_quote = current_page.find('"', start_link)
end_quote = current_page.find('"', start_quote+1)
hero_link = current_page[start_quote+1:end_quote]
print(hero_link)
end_bracket = current_page.find('>', end_quote+1)
start_bracket = current_page.find('<', end_bracket+1)
hero_name = current_page[end_bracket+1:start_bracket]
print(hero_name)
return start_bracket
start_bracket = 0
page_hero = '''<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt="蘇烈">蘇烈</a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt="百里玄策">百里玄策</a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt="百里守約">百里守約</a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt="鎧">鎧</a></li></ul>
'''
for i in range(4):
print('第%d個英雄:' % (i+1))
page_hero = page_hero[start_bracket:]
start_bracket = extract_info(page_hero)
輸出:
第1個英雄:
herodetail/194.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg
蘇烈
第2個英雄:
herodetail/195.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg
百里玄策
第3個英雄:
herodetail/196.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg
百里守約
第4個英雄:
herodetail/193.shtml
http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg
鎧
顯然,回圈和函式結合使用,實作了功能,并且進一步簡化代碼,
除了使用for回圈,還可以使用while回圈,如下:
# 使用函式實作
def extract_info(i, current_page):
start_link = current_page.find('<a href="')
start_quote = current_page.find('"', start_link)
end_quote = current_page.find('"', start_quote+1)
hero_info = current_page[start_quote+1:end_quote]
start_link = current_page.find('<img src="', end_quote+1)
start_quote = current_page.find('"', start_link)
end_quote = current_page.find('"', start_quote+1)
hero_link = current_page[start_quote+1:end_quote]
end_bracket = current_page.find('>', end_quote+1)
start_bracket = current_page.find('<', end_bracket+1)
hero_name = current_page[end_bracket+1:start_bracket]
if hero_info.startswith('hero'):
print('第%d個英雄:' % i)
print(hero_info)
print(hero_link)
print(hero_name)
return start_bracket
else:
return -1
start_bracket = 0
i = 1
page_hero = '''<ul class="herolist clearfix"><li><a href="herodetail/194.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/194/194.jpg" width="91px" alt="蘇烈">蘇烈</a></li><li><a href="herodetail/195.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/195/195.jpg" width="91px" alt="百里玄策">百里玄策</a></li><li><a href="herodetail/196.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/196/196.jpg" width="91px" alt="百里守約">百里守約</a></li><li><a href="herodetail/193.shtml" target="_blank"><img src="http://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" width="91px" alt="鎧">鎧</a></li></ul>
'''
while True:
page_hero = page_hero[start_bracket:]
start_bracket = extract_info(i, page_hero)
i += 1
if start_bracket == -1:
break
效果與前面一樣,
還有額外的代碼結構的練習,如有需要,可以直接點擊加QQ群
963624318 在群檔案夾商業資料分析從入門到入職中下載即可,
三、串列
之前的資料型別一般都是單個值,而不能再存盤像矩陣、陣列這種結構存盤多個元素,要是需要達到這樣的目標、需要使用新的資料型別,Python中提供了4種資料結構來存盤多個物件,稱它們為容器型別(Container Types),包括如下幾種型別:
- 串列List
- 元組Tuple
- 字典Dictionary
- 集合Set
1.創建串列
其實,字串其實也是一種序列,是由字符組成的序列,
字串可以通過切片訪問部分元素:
# sequence of characters
s="Corley!"
s[2:4]
輸出:
'rl'
字串是一個字符序列,串列是一個物件的序列,當物件的順序很重要時就會使用串列,
創建和訪問串列如下:
#sequence of anything
p = ['C','o','r','l','e','y','!']
p[2:4]
輸出:
['r', 'l']
可以看到,串列是用[]定義的,元素放入其中,用,隔開,
再如:
def how_many_days(month):
days_in_month=[31,28,31,30,31,30,31,31,30,31,30,31]
return days_in_month[month-1]
display(how_many_days(2), how_many_days(5), how_many_days(10))
輸出:
28
31
31
可以看到,直接獲取到了2、5、8月的天數,
還可以直接創建空串列,如下:
empty_list = []
another_empty_list = list()
display(empty_list,another_empty_list)
輸出:
[]
[]
可以看到,輸出了兩個空串列,
還可以從字串中分割出串列,如下:
weekday_str = 'Monday,Tuesday,Wednesday,Thursday,Friday'
weekdays = weekday_str.split(',')
weekdays
輸出:
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
以串列作為元素創建串列如下:
obj_list = ["string", 1, True, 3.14]
list_of_list = [empty_list, weekdays, obj_list]
list_of_list
輸出:
[[],
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
['string', 1, True, 3.14]]
此即串列的嵌套,
再如:
dal_memeber= [['Corley',18],['Jack',18],['Shirely',48],['Tom',18]]
print(dal_memeber)
print(dal_memeber[0])
print(dal_memeber[0][1])
輸出:
[['Corley', 18], ['Jack', 18], ['Shirely', 48], ['Tom', 18]]
['Corley', 18]
18
串列可以定位和切片如下:
display(weekdays[0],weekdays[1:3])
輸出:
'Monday'
['Tuesday', 'Wednesday']
還可以通過賦值改變串列中的元素,如下:
weekdays[0] = "Sunday"
weekdays
輸出:
['Sunday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
顯然,第一個元素已經改變,
2.洗掉元素
還可以洗掉串列中的元素,
一種方式是使用del關鍵字,基于下標洗掉,如下:
del weekdays[0]
weekdays
輸出:
['Tuesday', 'Wednesday', 'Thursday', 'Friday']
顯然,第一個元素被洗掉,
再如:
al = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
del al[3:]
al
輸出:
['A', 'B', 'C']
一次性洗掉多個元素,
還有一種方式是使用update()方法,基于元素洗掉,
如下:
weekdays.remove('Friday')
weekdays
輸出:
['Tuesday', 'Wednesday', 'Thursday']
但是如果串列中不存在這個元素時,會報錯,如下:
weekdays.remove('Friday')
weekdays
報錯:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-20-b508ecb8e563> in <module>
----> 1 weekdays.remove('Friday')
2 weekdays
ValueError: list.remove(x): x not in list
因為weekdays中沒有元素'Friday',因此會報錯,
此時可以先進行判斷,如果元素存在于串列中則洗掉,否則不洗掉;
判斷一個元素是否存在于串列中可以用in關鍵字,存在則回傳True,否則回傳False,
如下:
if 'Friday' in weekdays:
weekdays.remove('Friday')
else:
print('element not exists')
輸出:
element not exists
in的用法再如:
weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday']
'Friday' in weekdays
輸出:
True
還可以判斷某個元素是否不在串列中,如下:
'Fri' not in weekdays
輸出:
4
5
除了使用del和remove()洗掉元素,也可以使用pop()彈出元素,該方法不僅可以彈出元素,還能回傳被彈出的元素,如果未傳遞引數,則默認彈出并回傳最后一個元素,傳遞了下標引數則彈出并回傳相應的元素,
如下:
seasons = ['spring', 'summmer', 'autumn', 'winter']
last_season = seasons.pop()
print("last_season = ", last_season, "\nseasons = ", seasons)
輸出:
last_season = winter
seasons = ['spring', 'summmer', 'autumn']
再如:
first_season = seasons.pop(0)
print("first_season = ", first_season, "\nseasons = ", seasons)
輸出:
first_season = spring
seasons = ['summmer', 'autumn']
3.添加元素
向串列中添加元素也有多種方式:
一種是使用append()方法,該方法是將元素添加到串列末尾,
如下:
weekdays.append('Friday')
weekdays
輸出:
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Friday']
可以看到,串列中允許出現重復元素,
一種是insert()方法,可以指定位置添加元素,
如下:
weekdays.insert(0, 'Monday')
weekdays
輸出:
['Monday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Friday']
兩個串列也可以直接相加、形成新的串列,
如下:
weekend = ['Saturday', 'Sunday']
weekdays = weekdays + weekend
weekdays
輸出:
['Monday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Friday',
'Saturday',
'Sunday']
還可以根據元素獲取其再在串列中的下標位置:
display(weekdays.index('Thursday'),weekdays.index('Friday'))
輸出:
4
5
可以看到,有重復元素時,會回傳第一個下標,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/126583.html
標籤:其他


963624318 在群檔案夾商業資料分析從入門到入職中下載即可,