Python中的元組及字典經常使用方法舉例

1.元組

Python的元組與列表相似,不一樣之處在於元組的元素不能修改。html

元組使用小括號,列表使用方括號。python

元組建立很簡單,只須要在括號中添加元素,並使用逗號隔開便可。shell

    元組和列表十分類似django

    元組和字符串同樣是不能夠變的。安全

  • 元組能夠存儲一系列的值
  • 元組一般用在用戶定義的函數可以安全地採用一組值的時候,即被使用的元組的值不會改變。

以下實例:app

>>> t = (1,3,5,'a',(1,))
>>> type(t)
<class 'tuple'>
>>> print(t)
(1, 3, 5, 'a', (1,))

建立空元組函數

tup1 = ();

元組中只包含一個元素時,須要在元素後面添加逗號ui

tup1 = (50,);

元組操做:

    元組和字符串同樣屬於序列類型,能夠經過索引和切片操做spa

    元組值不可變code

    無組的拆分

>> t = (1,2,3)
>>> a,b,c = t
>>> print(t)
(1, 2, 3)
>>> print(a)
1
>>> print(b+c)
5
>>> t = (1,3,5,'a',(1,))
>>> type(t)
<class 'tuple'>
>>> print(t)
(1, 3, 5, 'a', (1,))
>>> print(t[1])
3

元組中引用變量:

>>> print(t)
(1, 2, 3)
>>> t1 = (t,4,5,"abc")
>>> print(t1)
((1, 2, 3), 4, 5, 'abc')

元組切片:    

>>> t1 = (t,4,5,"abc")
>>> print(t1)
((1, 2, 3), 4, 5, 'abc')
>>> x,y,z,m = t1
>>> print(x)
(1, 2, 3)
>>> print(m)
abc

  元組的方法:

(1) index()方法:查看元素下標是多少 

>>> t = (1,3,5,6,6,7,7,8)
>>> t.index(3)
1
>>> t.index(8)
7

  (2) conunt()方法:統計某無素的個數   

>>> t = (1,3,5,6,6,7,7,8)
>>> t.count(6)
2
>>> t.count(8)
1

元組中的內置函數:

1 len(tuple)
計算元組元素個數。
2 max(tuple)
返回元組中元素最大值。
3 min(tuple)
返回元組中元素最小值。
4 tuple(seq)
將列表轉換爲元組。

舉例以下:

>>> tuple1 = (1,2,3)
>>> tuple2 = (2,3,4,5)
>>> len(tuple1)
3
>>> max(tuple1)
3
>>> min(tuple1)
1

>>> list = [1,3,5,6,7]
>>> tuple(list)
(1, 3, 5, 6, 7)
>>> list
[1, 3, 5, 6, 7]

 

2.字典

字典是python中的惟一的映射類型(哈希表)

字典對象是可變的,可是字典的鍵必須使用不可變對象,一個字典中可使用不一樣類型的鍵值。

字典是另外一種可變容器模型,且可存儲任意類型對象。

字典的每一個鍵值 key=>value 對用冒號 : 分割,每一個鍵值對之間用逗號 , 分割,整個字典包括在花括號 {} 中 ,格式以下所示:

d = {key1 : value1, key2 : value2 }

鍵必須是惟一的,但值則沒必要。

值能夠取任何數據類型,但鍵必須是不可變的,如字符串,數字或元組。

字典的方法

  •     keys()
  •     values()
  •     get()
  •     items()

舉例以下:    

>>> dic = {'a':1,'b':2}
>>> dic
{'a': 1, 'b': 2}

>>> dic.keys()
dict_keys(['a', 'b'])

>>> dic.values()
dict_values([1, 2])

>>> len(dic)
2

>>> dic = {'a':1,'b':2}
>>> dic.get('b')
2

>>> dic["b"]
2

更改字典內value:

>>> dic
{'a': 1, 'b': 2}
>>> dic['a'] = 8
>>> dic
{'a': 8, 'b': 2}

查看key是否是在字典裏    

>>> dic
{'a': 1, 'b': 2}
>>> 'b' in dic
True
>>> "c" in dic
False

變爲列表:

>>> dic
{'a': 8, 'b': 2}
>>> dic.items()
dict_items([('a', 8), ('b', 2)])

複製字典:    

>>> dic
{'a': 8, 'b': 2}
>>> dic1 = dic.copy()
>>> dic1
{'a': 8, 'b': 2}

刪除字典內容:

>>> dic
{'a': 8, 'b': 2}
>>> dic.pop("a")
8
>>> dic
{'b': 2}

更新字典,兩個字典更新爲一個:

>>> dic
{'b': 2}
>>> dic1
{'a': 8, 'b': 2}
>>> dic.update(dic1)
>>> dic
{'b': 2, 'a': 8}

建立字典:

>>> dic = {}

>>> dic = dict()

>>> dict(a=1,b=2)
{'a': 1, 'b': 2}

>>> dict((["c",3],["d",4]))
{'c': 3, 'd': 4}

#fromkeys(),字典元素有相同的值時,默認爲None.
>>> dic.fromkeys('abcd') 
{'a': None, 'b': None, 'c': None, 'd': None}

#自動生成100個key,value默認爲100
dic.fromkeys(range(100),100)
{0: 100, 1: 100, 2: 100, 3: 100, 4: 100, 5: 100, 6: 100, 7: 10.....100:100}

訪問字典:

>>> dic1
{'a': 8, 'b': 2}
>>> dic["b"]
2

    for循環訪問:

>>> for k,v in dic1.items():print(k,v)
... 
a 8
b 2

 

Python3中經常使用的方法:

 幫助信息

  • help()查看幫助信息
>> help(list)
Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
  • dir() 看當前環境中變量
>>> dir()
['__builtins__', 'a', 'b', 'c', 'dic', 'dic1', 'django', 'django_manage_shell', 'i', 'input', 'k', 'list', 'm', 'sys', 't', 't1', 'tuple1', 'tuple2', 'v', 'x', 'y', 'z']

類型轉換:

  • str()  
  • int()   
  • list()  
  • dict()  
  • tuple()

自動生成序列:

  range()          

>>> for i in range(10):print(i)
... 
0
1
2
3
4
5
6
7
8
9

       

可迭代的,循環取值

    items()

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------
list1 = {1:1,2:2,3:3}
for i in list1.items():
    print(i)


#結果:
(1, 1)
(2, 2)
(3, 3)

默認輸入都爲字符串:

  input ()

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------

x = input("x = ")
print(x)

  

求長度:

    len()

>>> list
[1, 3, 5, 6, 7]
>>> len(list)
5

看類型:

    type()

>>> type(list)
<class 'list'>

a是否是什麼類型

 

    isinstance(a,list)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------
list1 = [1,3,5]
print(list1)
a=isinstance(list1,list)
print(a)

#結果
[1, 3, 5]
True

有沒有某屬性

    print(hasttr(l1,"append"))

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------
list1 = [1,3,5]
print(list1)
a=hasattr(list1,"append")
print(a)

#結果
[1, 3, 5]
True

 

打印結果:

    print()

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------
a="hello fengxiaoqing"
print(a)

#結果:
hello fengxiaoqing

生成可迭代列表,(index,value)

    enumerate()

>>> for i in enumerate(list):
...     print(i)
...         
(0, 1)
(1, 3)
(2, 5)
(3, 6)
(4, 7)
相關文章
相關標籤/搜索