Python的元組()與字典{}

小周啊發表於2019-05-14

元組tuple

我們在定義變數之前,最好先申明該變數的型別,如

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

當我們定義一個相同元素時,不一樣的寫法將得到不一樣的資料型別

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

在tuple型別中,單個元素一定要加“,”逗號,否則無法識別為tuple型別。

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形式的一種表達形式,字典可以儲存任意的物件,也可以是不同的資料型別。

# 字典的三種定義方式
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`}

方法:

# 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]

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 + 滑鼠左鍵

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


相關文章