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

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

2020-09-25 15:57:26 其他

文章目錄

  • 一、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/qita/126583.html

標籤:其他

上一篇:強化學習演算法復現(一):k臂賭博機問題

下一篇:一篇文章帶你使用 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)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more