python基礎資料類型

來源:互聯網
上載者:User

標籤:mat   lex   set   new   基礎   world   zhang   pytho   存在   

1,int #數字(整形)

a=1
print(type(a)) ###結果 <class ‘int‘>

2,bool #布爾值True與False

非0為真,非空為真

print(bool(9))
True


3,str #字串

單雙引號引起來的就是str

a="123"

print(type(a))

<class ‘str‘>

##字串的格式化輸出


 
name=‘name‘age=99a="%s-%dqqqqq"%(name,age)print(a) 

format ##格式化輸出的另一種方式
a="hello world {name}"
print(a.format(name="format"))
hello world format

##字串拼接

a=‘sqw‘
b=‘aaaaaaa‘
print(a+b)

  

 


4,tupe (1,2,3)#元祖 tuple #元祖不可改變

括弧括起來的就是元祖(元祖是不可改變的)

a=(‘1‘,‘a‘)
print(type(a))
<class ‘tuple‘>

###元祖刪查操作(元祖不可更改)

##查
t1=(‘a‘,‘1‘,‘qeqw‘,12)
print(t1[2]) ###‘qeqw‘

##刪

del t1

 

5,list[1,2,3,‘abc‘] #列表 list

a=[‘a‘,‘wqe‘,1]

查
索引(下標) ,都是從0開始
切片
count 查某個元素的出現次數
index 根據內容找其對應的位置

增加
append() 追加
insert(index, "內容")
extend 擴充

修改
a[index] = "新的值"
a[start:end] = [a,b,c]

刪除
remove("內容")
pop(index)
del a, del a[index]
clear() 清空

  

6,dict{‘name‘:‘alex‘} #字典 dict

dic={‘name‘:‘alex‘}

dic1={}
dic2=dict(((‘name‘,‘alex‘),))
print(dic2)

dic3=dict([[‘name‘,‘alex‘],])
print(dic3)

dic1={‘name‘:‘alex‘}
dic1[‘age‘]=18
print(dic1)

##增
dic1["zen"]=12

鍵存在,不改動,返回字典中相應的鍵對應的值
ret=dic1.setdefault(‘age‘,34)
print(ret)


鍵不存在,在字典中中增加新的索引值對,並返回相應的值
ret2=dic1.setdefault(‘hobby‘,‘girl‘)
print(dic1)
print(ret2)


##刪
dle dic1 ##刪除字典
dle dic["zen"] #刪除這對索引值
dic3=dic1.fromkeys(["a","b","c"],"aaa") ##a,b,c 鍵的值都為“aaa”(用list也一樣)如果改一個值、其他值也會變
print(dic3)


#查 通過鍵去尋找
dic3={‘age‘: 18, ‘name‘: ‘alex‘, ‘hobby‘: ‘girl‘}

print(dic3[‘name‘])

print(list(dic3.keys())) ## keys 取鍵
print(list(dic3.values())) ## values 取值
print(list(dic3.items())) ## items 拿出所有索引值對

dic3={‘age‘: 18, ‘name‘: ‘alex‘, ‘hobby‘: ‘girl‘}
dic3[‘age‘]=55
print(dic3)

###get (有鍵就傳回值,沒有就返回None)
d={"name":"zhangbin","age":"23"}
print(d.get("name")) 結果 ##zhangbin
print(d.get("sex")) 結果 ##None
print(d.get("sex","male")) 結果 ##male

##update修改
dic4={‘age‘: 18, ‘name‘: ‘alex‘, ‘hobby‘: ‘girl‘}
dic5={‘1‘:‘111‘,‘2‘:‘222‘}
dic5={‘1‘:‘111‘,‘name‘:‘222‘}

dic4.update(dic5) #在dic4中添加dic5字典的類容(不修改dic5),如果有相同的鍵就覆蓋
print(dic4)
print(dic5)

 

python基礎資料類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.