主頁 > 軟體設計 > 商業資料分析從入門到入職(6)Python程式結構和函式

商業資料分析從入門到入職(6)Python程式結構和函式

2020-09-24 11:50:32 軟體設計

文章目錄

  • 一、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群 Python極客部落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 code blocks

前面也看到,出現了很多以#開頭的代碼和文字性說明,代碼顏色也是和其他代碼有所區別的,這就是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        

輸出如下:
python while loop 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回圈同時出現的還有rangerange(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群 Python極客部落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

除了使用delremove()洗掉元素,也可以使用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/ruanti/118717.html

標籤:其他

上一篇:從無到有,電腦小白學python

下一篇:一篇文章帶你使用 Python搞定對 Excel 表的讀寫和處理(xlsx檔案的處理)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 面試突擊第一季,第二季,第三季

    第一季必考 https://www.bilibili.com/video/BV1FE411y79Y?from=search&seid=15921726601957489746 第二季分布式 https://www.bilibili.com/video/BV13f4y127ee/?spm_id_fro ......

    uj5u.com 2020-09-10 05:35:24 more
  • 第三單元作業總結

    1.前言 這應該是本學期最后一次寫作業總結了吧。總體來說,對作業的節奏也差不多掌握了,作業做起來的效率也更高了。雖然和之前的作業一樣,作業中都要用到新的知識,但是相比之前,更加懂得了如何利用工具以及資料。雖然之間卡過殼,但總體而言,這幾次作業還算完成的比較好。 2.作業程序總結 相比前兩個單元,此單 ......

    uj5u.com 2020-09-10 05:35:41 more
  • 北航OO(2020)第四單元博客作業暨課程總結博客

    北航OO(2020)第四單元博客作業暨課程總結博客 本單元作業的架構設計 在本單元中,由于UML圖具有比較清晰的樹形結構,因此我對其中需要進行查詢操作的元素進行了包裝,在樹的父節點中存盤所有孩子的參考。考慮到性能問題,我采用了快取機制,一次查詢后盡可能快取已經遍歷過的資訊,以減少遍歷次數。 本單元我 ......

    uj5u.com 2020-09-10 05:35:48 more
  • BUAA_OO_第四單元

    一、UML決議器設計 ? 先看下題目:第四單元實作一個基于JDK 8帶有效性檢查的UML(Unified Modeling Language)類圖,順序圖,狀態圖分析器 MyUmlInteraction,實際上我們要建立一個有向圖模型,UML中的物件(元素)可能與同級元素連接,也可與低級元素相連形成 ......

    uj5u.com 2020-09-10 05:35:54 more
  • 6.1邏輯運算子

    邏輯運算子 1. && 短路與 運算式1 && 運算式2 01.運算式1為true并且運算式2也為true 整體回傳為true 02.運算式1為false,將不會執行運算式2 整體回傳為false 03.只要有一個運算式為false 整體回傳為false 2. || 短路或 運算式1 || 運算式2 ......

    uj5u.com 2020-09-10 05:35:56 more
  • BUAAOO 第四單元 & 課程總結

    1. 第四單元:StarUml檔案決議 本單元采用了圖模型決議UML。 UML檔案可以抽象為圖、子圖、邊的邏輯結構。 在實作中,圖的節點包括類、介面、屬性,子圖包括狀態圖、順序圖等。 采用了三次遍歷UML元素的方法建圖,第一遍遍歷建點,第二、三次遍歷設定屬性、連邊,實作圖物件的初始化。這里借鑒了一些 ......

    uj5u.com 2020-09-10 05:36:06 more
  • 談談我對C# 多型的理解

    面向物件三要素:封裝、繼承、多型。 封裝和繼承,這兩個比較好理解,但要理解多型的話,可就稍微有點難度了。今天,我們就來講講多型的理解。 我們應該經常會看到面試題目:請談談對多型的理解。 其實呢,多型非常簡單,就一句話:呼叫同一種方法產生了不同的結果。 具體實作方式有三種。 一、多載 多載很簡單。 p ......

    uj5u.com 2020-09-10 05:36:09 more
  • Python 資料驅動工具:DDT

    背景 python 的unittest 沒有自帶資料驅動功能。 所以如果使用unittest,同時又想使用資料驅動,那么就可以使用DDT來完成。 DDT是 “Data-Driven Tests”的縮寫。 資料:http://ddt.readthedocs.io/en/latest/ 使用方法 dd. ......

    uj5u.com 2020-09-10 05:36:13 more
  • Python里面的xlrd模塊詳解

    那我就一下面積個問題對xlrd模塊進行學習一下: 1.什么是xlrd模塊? 2.為什么使用xlrd模塊? 3.怎樣使用xlrd模塊? 1.什么是xlrd模塊? ?python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫。 今天就先來說一下xl ......

    uj5u.com 2020-09-10 05:36:28 more
  • 當我們創建HashMap時,底層到底做了什么?

    jdk1.7中的底層實作程序(底層基于陣列+鏈表) 在我們new HashMap()時,底層創建了默認長度為16的一維陣列Entry[ ] table。當我們呼叫map.put(key1,value1)方法向HashMap里添加資料的時候: 首先,呼叫key1所在類的hashCode()計算key1 ......

    uj5u.com 2020-09-10 05:36:38 more
最新发布
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:20:47 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:20:25 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:20:17 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:20:10 more
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:19:44 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:19:07 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:18:57 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:18:49 more
  • 05單件模式

    #經典的單件模式 public class Singleton { private static Singleton uniqueInstance; //一個靜態變數持有Singleton類的唯一實體。 // 其他有用的實體變數寫在這里 //構造器宣告為私有,只有Singleton可以實體化這個類! ......

    uj5u.com 2023-04-19 08:42:51 more
  • 【架構與設計】常見微服務分層架構的區別和落地實踐

    軟體工程的方方面面都遵循一個最基本的道理:沒有銀彈,架構分層模型更是如此,每一種都有各自優缺點,所以請根據不同的業務場景,并遵循簡單、可演進這兩個重要的架構原則選擇合適的架構分層模型即可。 ......

    uj5u.com 2023-04-19 08:42:41 more