重拾python筆記三的簡單介紹

本文目錄一覽:

python 筆記記錄怎麼歸納整理

可以到“馬克筆記”上面,記錄下來,以書籍的形式展示,記錄後還可以生成PDF等文件用於在kindle等設備複習。方便下次觀看。

你可以嘗試下這個平台。

python自學筆記13:元組和字典的操作

定義元組(tuple):

t1=(1,2,3,4)#多個數據元組

t2=(1,)#如果元組內只有一個數據,也需要手逗號隔開,否則這個數據將是他本身的類型。

元組的操作:

元組類型數據不支持修改,可查找

查找:

按下標查找:

print(t1[1])

函數查找:

print(t1.index(1))返回對應下標,如果數據不存在,程序將報錯

print(t1.count(1))統計數據在元組當中出現的次數

print(len(t1))統計元組當中的數據個數

注意:當元組內嵌套列表數據,可以通過下標的方法對列表數據進行修改如:

t3=(1,2,[“a”,”b”])

t3[2][0]=c #t3的值將變為(1,2,[“c”,”b”])

——————————————————

——————————————————

定義字典(dict)

字典的特點

1:符號為{}

2:數據為鍵(key)值(value)對形式,每個鍵值對之間用逗號隔開如:

dict1={“name”:”小明”,”age”:18,”gender:男”}

字典的操作:

dict1[“name”]=”小紅”

dict1[“id”]=3

如果key存在,將修改其所對應的值。如果不存在,將在字典最後添加該鍵值對

2.刪除數據

del():刪除字典或刪除字典內的鍵值對

del dict1[“name”] 刪除字典內的鍵值對,如果刪除的key不存在,程序將會報錯

del(del)刪除字典

clear(dict1) 清空字典

3.查找數據

一.按照key進行查找,最後返回相對應的值

二.按函數進行查找:

(1) get(key,默認值):

如果查找的key不存在則返回所寫的默認值,如果不寫默認值則返回None

dict1={“name”:”小明”,”age”:18,”gender:男”}

print(dict1.get(“name”)) #小明

print(dict1.get(“id”,110)) # 110

——————————————————

(2) keys():返回字典內的所有key 可用for遍歷

print(dict1.keys())

返回 [“name”,”age”,”gender”]

for key in dict1.keys():

..print(key)

逐行輸出name age gender

——————————————————

(3) values(): 返回字典內的值 可用for遍歷

print(dict1.values())

返回[“小明”,18,”男”]

for value dict1.values():

..print(value)

逐行輸出小明 18 男

——————————————————

(4) items():將字典內的數據以元組的形式返回

print(dict1.items()) 可用for遍歷

返回[(“name”,”小明”),(“age”,18),(“gender”,”男”)]

for item in dict1.items():

..print(item)

逐行輸出 (“name”,”小明”) (“age”,18)(“gender”,”男”)

——————————————————

遍歷字典鍵值對(拆包) 可在for內使用兩個臨時變量

dict1={“name”:”小明”,”age”:18,”gender:男”}

for key,value in dict1.items():

..print(f”{key}=value”)

逐行輸出:

name=小明 age=18 gender=男

python3.4學習筆記 3.x和2.x的區別,持續更新

python3.4學習筆記(四) 3.x和2.x的區別

在2.x中:print html,3.x中必須改成:print(html)

import urllib2

ImportError: No module named ‘urllib2’

在python3.x裡面,用urllib.request代替urllib2

import thread

ImportError: No module named ‘thread’

在python3.x裡面,用_thread(在前面加一個下劃線)代替thread

在2.x中except Exception,e : 3.x中改為except (Exception):

=================================

print函數

雖然print語法是Python 3中一個很小的改動,且應該已經廣為人知,但依然值得提一下:Python 2中的print語句被Python 3中的print()函數取代,這意味着在Python 3中必須用括號將需要輸出的對象括起來。

在Python 2中使用額外的括號也是可以的。但反過來在Python 3中想以Python2的形式不帶括號調用print函數時,會觸發SyntaxError。

Python 2.7.6

print ‘Python’, python_version()

print ‘Hello, World!’

print(‘Hello, World!’)

print “text”, ; print ‘print more text on the same line’

輸出:

Hello, World!

Hello, World!

text print more text on the same line

—————————

Python 3.4.1

print(‘Python’, python_version())

print(‘Hello, World!’)

print(“some text,”, end=””)

print(‘ print more text on the same line’)

輸出:

Hello, World!

some text, print more text on the same line

print ‘Hello, World!’

File “ipython-input-3-139a7c5835bd”, line 1

print ‘Hello, World!’

^

SyntaxError: invalid syntax

注意:在Python中,帶不帶括號輸出”Hello World”都很正常。

但如果在圓括號中同時輸出多個對象時,就會創建一個元組,這是因為在Python 2中,print是一個語句,而不是函數調用。

print ‘Python’, python_version()

print(‘a’, ‘b’)

print ‘a’, ‘b’

Python 2.7.7

(‘a’, ‘b’)

a b

———————————

整數除法

由於人們常常會忽視Python 3在整數除法上的改動(寫錯了也不會觸發Syntax Error),所以在移植代碼或在Python 2中執行Python 3的代碼時,需要特別注意這個改動。

所以,我還是會在Python 3的腳本中嘗試用float(3)/2或 3/2.0代替3/2,以此來避免代碼在Python

2環境下可能導致的錯誤(或與之相反,在Python 2腳本中用from __future__ import division來使用Python

3的除法)。

Python 2.7.6

3 / 2 = 1

3 // 2 = 1

3 / 2.0 = 1.5

3 // 2.0 = 1.0

Python 3.4.1

3 / 2 = 1.5

3 // 2 = 1

3 / 2.0 = 1.5

3 // 2.0 = 1.0

———————————

Unicode

Python 2有基於ASCII的str()類型,其可通過單獨的unicode()函數轉成unicode類型,但沒有byte類型。

而在Python 3中,終於有了Unicode(utf-8)字符串,以及兩個字節類:bytes和bytearrays。

Python 2.7.6

print type(unicode(‘this is like a python3 str type’))

type ‘unicode’

print type(b’byte type does not exist’)

type ‘str’

print ‘they are really’ + b’ the same’

they are really the same

print type(bytearray(b’bytearray oddly does exist though’))

type ‘bytearray’

Python 3.4.1 has class ‘bytes’

print(‘and Python’, python_version(), end=””)

print(‘ also has’, type(bytearray(b’bytearrays’)))

and Python 3.4.1 also has class ‘bytearray’

1

‘note that we cannot add a string’ + b’bytes for data’

—————————————————————————

TypeError Traceback (most recent call last)

ipython-input-13-d3e8942ccf81 in module()

—- 1 ‘note that we cannot add a string’ + b’bytes for data’

TypeError: Can’t convert ‘bytes’ object to str implicitly

=================================

python 2.4 與 python 3.0 的比較

一、 print 從語句變為函數

原: print 1,2+3

改為: print ( 1,2+3 )

二、range 與 xrange

原 : range( 0, 4 ) 結果 是 列表 [0,1,2,3 ]

改為:list( range(0,4) )

原 : xrange( 0, 4 ) 適用於 for 循環的變量控制

改為:range(0,4)

三、字符串

原: 字符串以 8-bit 字符串存儲

改為: 字符串以 16-bit Unicode 字符串存儲

四、try except 語句的變化

在2.x中except Exception,e : 3.x中改為except (Exception):

五、打開文件

原: file( ….. )

或 open(…..)

改為:

只能用 open(…..)

六、從鍵盤錄入一個字符串

原: raw_input( “提示信息” )

改為: input( “提示信息” )

七、bytes 數據類型

A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 = x 256.

bytes 可以看成是“字節數組”對象,每個元素是 8-bit 的字節,取值範圍 0~255。

由於在 python 3.0中字符串以 unicode 編碼存儲,當寫入二進制文件時,字符串無法直接寫入(或讀取),必須以某種方式的編碼為字節序列後,方可寫入。

(一)字符串編碼(encode) 為 bytes

例: s = “張三abc12”

b = s.encode( 編碼方式)

# b 就是 bytes 類型的數據

# 常用的編碼方式為 : “uft-16” , “utf-8”, “gbk”, “gb2312”, “ascii” , “latin1” 等

# 注 : 當字符串不能編碼為指定的“編碼方式”時,會引發異常

(二) bytes 解碼(decode)為字符串

s = “張三abc12”

b = s.encode( “gbk”) # 字符串 s 編碼為 gbk 格式的字節序列

s1 = b.decode(“gbk”) # 將字節序列 b以gbk格式 解碼為字符串

# 說明,當字節序列不能以指定的編碼格式解碼時會引發異常

(三)使用方法舉例

#coding=gbk

f = open(“c:\\1234.txt”, “wb”)

s = “張三李四abcd1234”

# ——————————-

# 在 python2.4 中我們可以這樣寫:

# f.write( s )

# 但在 python 3.0中會引發異常

# ——————————-

b = s.encode(“gbk”)

f.write( b )

f.close()

input(“?”)

讀取該文件的例子:

#coding=gbk

f = open(“c:\\1234.txt”, “rb”)

f.seek(0,2) #定位至文件尾

n = f.tell() #讀取文件的字節數

f.seek(0,0) #重新定位至文件開始處

b = f.read( n )

# ——————————

# 在 python 2.4 中 b 是字符串類型

# 要 python 3.0 中 b 是 bytes 類型

# 因此需要按指定的編碼方式確碼

# ——————————

s = b.decode(“gbk”)

print ( s )

# ——————————

# 在 python 2.4 中 可以寫作 print s 或 print ( s )

# 要 python 3.0 中 必須寫作 print ( s )

# ——————————

f.close()

input(“?”)

運行後應顯示:

張三李四abcd1234

(四) bytes序列,一但形成,其內容是不可變的,例:

s=”ABCD”

b=s.encode(“gbk”)

print b[0] # 顯示 65

b[0] = 66

# 執行該句,出現異常: ‘bytes’ object does not support item assignment

八、 chr( K ) 與 ord( c )

python 2.4.2以前

chr( K ) 將編碼K 轉為字符,K的範圍是 0 ~ 255

ord( c ) 取單個字符的編碼, 返回值的範圍: 0 ~ 255

python 3.0

chr( K ) 將編碼K 轉為字符,K的範圍是 0 ~ 65535

ord( c ) 取單個字符的編碼, 返回值的範圍: 0 ~ 65535

九、 除法運算符

python 2.4.2以前

10/3 結果為 3

python 3.0

10 / 3 結果為 3.3333333333333335

10 // 3 結果為 3

十、字節數組對象 — 新增

(一) 初始化

a = bytearray( 10 )

# a 是一個由十個字節組成的數組,其每個元素是一個字節,類型借用 int

# 此時,每個元素初始值為 0

(二) 字節數組 是可變的

a = bytearray( 10 )

a[0] = 25

# 可以用賦值語句更改其元素,但所賦的值必須在 0 ~ 255 之間

(三) 字節數組的切片仍是字節數組

(四) 字符串轉化為字節數組

#coding=gbk

s =”你好”

b = s.encode( “gbk”) # 先將字符串按某種“GBK”編碼方式轉化為 bytes

c = bytearray( b ) #再將 bytes 轉化為 字節數組

也可以寫作

c = bytearray( “你好”, “gbk”)

(五) 字節數組轉化為字符串

c = bytearray( 4 )

c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68

s = c.decode( “gbk” )

print ( s )

# 應顯示: ABCD

(六) 字節數組可用於寫入文本文件

#coding=gbk

f = open(“c:\\1234.txt”, “wb”)

s = “張三李四abcd1234”

# ——————————-

# 在 python2.4 中我們可以這樣寫:

# f.write( s )

# 但在 python 3.0中會引發異常

# ——————————-

b = s.encode(“gbk”)

f.write( b )

c=bytearray( “王五”,”gbk”)

f.write( c )

f.close()

input(“?”)

python3筆記12:%的用法

我們還可以用詞典來傳遞真實值。如下:

格式符為真實值預留位置,並控制顯示的格式。格式符可以包含有一個類型碼,用以控制顯示的類型,如下:

%s 字符串 (採用str()的顯示)

%r 字符串 (採用repr()的顯示)

%c 單個字符

%b 二進制整數

%d 十進制整數

%i 十進制整數

%o 八進制整數

%x 十六進制整數

%e 指數 (基底寫為e)

%E 指數 (基底寫為E)

%f 浮點數

%F 浮點數,與上相同

%g 指數(e)或浮點數 (根據顯示長度)

%G 指數(E)或浮點數 (根據顯示長度)

%% 字符”%”

上面的width, precision為兩個整數。我們可以利用*,來動態代入這兩個量。比如:

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/277795.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-19 13:21
下一篇 2024-12-19 13:21

相關推薦

  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論