主頁 > 後端開發 > 商業資料分析從入門到入職(6)Python程式結構和函式

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

2020-09-24 11:21:23 後端開發

文章目錄

  • 一、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/houduan/118589.html

標籤:python

上一篇:CSDN好像很贊。在學習C

下一篇:求大神幫忙解決 坐等

標籤雲
其他(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)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more