一 python元組tuple型別
元組t= (1, 2, 3, 4)是不可變型別,屬於序列,但頂層元素不可變,僅支援count()和index()操作。
-*- coding:utf-8 -*-# 不可變型別t = ( 0, '
ni', 1, 2, 3
)t = t + tuple("
spam")
for x in
t: print(x)
t = [ x*2
for x in
t ]t = [ x for x in ['
b', '
c', '
a', 'd'
]]t =tuple(t)
tmp =list(t).sort() # sort()為列表物件排序操作,不返回值
print(tmp) # 列印none
# tuple 僅有兩個的操作if"
aa"int:
print( t.index("aa
") )
print( t.count('bb
') )
# 元組不可變性只支援頂層
t = ( 2, 3, [4, 5], 6
)
二 檔案型別
f = open( filename, mode ) ,read(), readline(), readlines(),write(), close()
# 檔案myfile = open('
myfile.txt
', 'w'
)myfile.write(
"python file text,\n")
myfile.write(
"end of text file.\n")
myfile.close()
# 迭代操作
myfile = open('
myfile.txt
', 'r'
)s =myfile.read()
print(s)
myfile.close()
for line in open('
myfile.txt'):
print(line, end=''
)myfile.close()
# 檔案儲存和解析python
object
x, y, z = 11, 23, 45
s = '
spam
'd =
l = [ i for i in range(5
)]f = open("
datafile.txt
", 'w'
)f.write( s + '\n'
)f.write(
"%s,%s,%s\n
" %(x, y, z) )
f.write(str(l) + '
$'+ str(d) + '\n'
) # 物件轉化為字串儲存,$區分
f.close()
"""chars = open("
datafile.txt
").read()
print(chars)
"""# convert str into python object
f = open("
datafile.txt")
line =f.readline()
print( line.rstrip() )
line =f.readline()
numbers = [ int(x) for x in
line ]
print(numbers)
# convert list and dict
line =f.readline()
parts = line.split("
$") # eval(): convert str into object
print( [eval(p)
for p in
parts] )
f.close()
pickle持久化儲存python原生物件
import picklef = open("
datafile.pkl
", 'wb'
)d =
pickle.dump(d, f) # 物件序列化
f.close()
f = open("
datafile.pkl
", 'rb'
)e =pickle.load(f)
print(e)
# bool true flase 數字0為flase,其他都為真 空物件都為假
ifbool(1) != bool
(): print(
bool('
spam
') )
if type(1) !=type():
print( isinstance([
1], list) )
# 避免迴圈引用 l = ["
refer
"# print(value, ..., sep='
', end='
\n', file=sys.stdout, flush=false)
a, b, c , *d= [1, 2, 3, 4, 5, 6
]print(a, b, c, sep="
| ", end ="!n"
)log = open("
textfile.txt
", "w"
) print( a, b, c, d, sep="
***", end="
\n", file =log)
log.close()
# print函式預設將物件傳入到stdout中,顯示
import sys
sys.stdout.write(
"hello\n
")
python13檔案 13 Python 檔案
概述 嚴格講,檔案不屬於資料型別。02操作 1 開啟檔案 1 基本語法 file open 檔名 mode 引數mode模式可選引數,分為 r讀 w寫 a追加 r w a後面可接第二個引數,b標書二進位制,f open data.bin rb 2 完整語法格式為 open file,mode r b...
python3元組 Python3元組
python的元組與列表相似,不同之處在於元組的元素不能修改 元組使用小括號,列表使用方括號 元組建立很簡單,只需要在括號中新增元素,並使用逗號隔開即可。建立空元組 tup1 tup2 1,元組只包含乙個元素時,需要在元素後面新增逗號,否則括號會被當作運算子使用 元組與字串類似,下標索引從0開始,可...
python雜記(3) 元組與函式
1 元組 元組tuple,與列表有很多類似。區別主要是元組中的元素是不可改變的 它的定義使用 而不是 tuple1 1 2,3 4,5 6 print tuple1 2 tuple2 123 abc pht 123 456 tuple2 tuple2 2 哈哈 tuple2 2 元組的插入,哈哈 的...