Python的元組()與字典 { }

元組tuple

咱們在定義變量以前,最好先申明該變量的類型,如git

l=list()                  # l爲列表
print(l)
t=tuple()              # t爲元組
print(t)

當咱們定義一個相同元素時,不同的寫法將獲得不同的數據類型api

a1=(1)
a2=(1,)
print(type(a1))
# <class 'int'>
print(type(a2))
# <class 'tuple'>

在tuple類型中,單個元素必定要加「,」逗號,不然沒法識別爲tuple類型。ssh

m = (1,2,3,43,4,6,1,3,4,4)
# count(value) 統計value的個數
print(m.count(1))
# 2
# index(value) 返回第一個value元素的下標
print(m.index(4))
# 4
print(m.index(2))
# 1

字典dict

字典是咱們在其餘應用中用到的keys:values形式的一種表達形式,字典能夠存儲任意的對象,也能夠是不一樣的數據類型。ide

# 字典的三種定義方式
d1 = dict(name = "zhou",age = 22)
print(d1)
# {'name': 'zhou', 'age': 22}

d2 = {"id":43245232,"name":"zhoumoumou"}
print(d2)
# {'id': 43245232, 'name': 'zhoumoumou'}

d3 = dict([("ip","1.1.1.1"),("address","ChangSha")])
print(d3)
# {'ip': '1.1.1.1', 'address': 'ChangSha'}

方法:spa

# get(key) 根據key獲取value
print(d1.get("name"))
# zhou
print(d1.get("address"))
# None

# setdefault 根據key獲取value,若是key不存在,能夠設定默認的value
print(d1.setdefault("name"))
# zhou
print(d1.setdefault("address","ChangSha"))
# ChangSha

# 獲取全部的keys值
print(d2.keys())
# dict_keys(['id', 'name'])
print(type(d2.keys()))
# <class 'dict_keys'>
# 獲取全部的values值
print(d2.values())
# dict_values([43245232, 'zhoumoumou'])
print(type(d2.values()))
# <class 'dict_values'>
for x,y in d3.items():
print("key = {0},value = {1}".format(x,y))
# key = ip,value = 1.1.1.1
# key = address,value = ChangSha

update 和list中的 + 相似
l=list() l+=[1,2,3,4]code

m=dict()
n=dict(name="zhou",age=12)
m.update(n)
print(m)
# {'name': 'zhou', 'age': 12}
# l=list() l+=[1,2,3,4]
l=list()
m = [1,2,3,4,5,6]
l+=m
print(l)
# [1, 2, 3, 4, 5, 6]
print(d3)
# pop(key) 刪除key所對應的元素
keyDelete = d3.pop("ip")
print(keyDelete)
print(d3)

其餘經常使用操做

help() ctrl + 鼠標左鍵orm

s="dedwefwfrgwr"
# help(s.split())
result = s.startswith("de")
print(result)
# True
# dir()
print(dir(s))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
# '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
# '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
# '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
# '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
# '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__',
# '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center',
# 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
# 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
# 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
# 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',
# 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
# 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
# 'swapcase', 'title', 'translate', 'upper', 'zfill']
# type()
a="123"
print(type(a))
# <class 'str'>
print(type(int(a)))
# <class 'int'>
# isinstance(a,type) 返回值是一個bool類型
print(isinstance(s,str))
# True
print(isinstance(s,dict))
# False
相關文章
相關標籤/搜索