1. 程式人生 > >python元組 字典 集合

python元組 字典 集合

python 元組 字典 集合

1.列表構建棧的數據結構:
棧的特點:先進後出

#!/usr/bin/env python
#coding:utf-8   
stack = []

info = """

            棧結構
    1.入棧
    2.出棧
    3.棧長度
    4.棧頂元素
    5.退出

"""
print info

while 1:
    choice = raw_input("請輸入你的選擇:")

    if choice == "1":
        in_value = raw_input("入棧元素:")
        stack.append(in_value)
        print "元素%s入棧成功!" %(in_value)
        print stack
    elif choice   == "2":
        if stack:
            out_value = stack.pop()
            print "元素%s出棧成功!" %(out_value)
            print stack
        else:
            print "棧為空!"
    elif choice == "3":
        print "棧長度為%d" %(len(stack))
    elif choice == "4":
        if stack:
            print "棧頂元素為%s" %(stack[-1])
        else:
            print "棧為空"
    elif choice == "5":
        exit(0)
    else:
        print "請輸入正確選擇!"

測試結果:
技術分享圖片

2.列表構建隊列的數據結構:
隊列的特點:先進先出

#!/usr/bin/env python
#coding:utf-8
queue = []

info = """

            隊列結構
    1.入隊
    2.出隊
    3.隊長度
    4.隊頭元素
    5.隊尾元素
    6.退出

"""
print info

while 1:
    choice = raw_input("請輸入你的選擇:")

    if choice == "1":
        in_value = raw_input("入隊元素:")
        queue.append(in_value)
        print "元素%s入隊成功!" % (in_value)
        print queue
    elif choice == "2":
        if queue:
            out_value = queue.pop(0)
            print "元素%s出隊成功!" % (out_value)
            print queue
        else:
            print "隊為空!"
    elif choice == "3":
        print "隊長度為%d" % (len(queue))
    elif choice == "4":
        if queue:
            print "隊頭元素為%s" % (queue[0])
        else:
            print "隊為空"
    elif choice == "5":
        if queue:
            print "隊尾元素為%s" % (queue[-1])
        else:
            print "隊為空"
    elif choice == "6":
        exit(0)
    else:
        print "請輸入正確選擇!"

測試結果:
技術分享圖片

3.Is和等於號的區別:
字符串駐留機制:

  • 對於較小的字符串,id相同
  • 對於較長的字符串,id不相同,因為不會駐留字符串的副本。
    註意:在進行測試時,一定要在交互式環境測試。
    測試:
    
    In [1]: a = ‘hello‘

In [2]: b = ‘hello‘

In [3]: print id(a),id(b)
40886560 40886560

In [4]: c = ‘hello java world‘

In [5]: d = ‘hello java world‘

In [6]: print id(c), id(d)
40923296 40923464

In [7]: print c is d

False

In [8]: e = ‘python‘

In [9]: f = "".join([‘p‘, ‘y‘, ‘t‘, ‘h‘, ‘o‘, ‘n‘])

In [10]: print id(e), id(f)
140309747759888 40886608


結論:
Is表示的是對象標識符;表示兩個變量的值是否在統一塊內存空間;
== 表示的是值是否相等

總結: is返回值為True, ==返回一定是True;
深拷貝與淺拷貝:
 1. 直接賦值, 只是把新的變量指向li的內存空間, 沒有復制;當li改變, li1也隨之改變;

In [11]: li = [1, 2, 3]

In [12]: li1 = li

In [13]: id(li)
Out[13]: 40893688

In [14]: id(li1)
Out[14]: 40893688


2. 淺拷貝: 拷貝出一份副本, 但是沒有拷貝子對象(列表裏面的列表對象);不完全拷貝
- 切片li[:]      

In [15]: li1 = li[:]

In [16]: id(li), id(li1)
Out[16]: (40893688, 40891672)

  • copy.copy()
    In [17]: li = [‘fentiao‘, ‘zhurou‘, [‘fensi‘, ‘fendai‘]]

In [18]: li1 = li[:]

In [19]: id(li), id(li1)
Out[19]: (40891600, 40878592)

In [20]: id(li[-1]), id(li[-1])
Out[20]: (40906264, 40906264)

In [21]: import copy

In [22]: li2 = copy.copy(li)

In [23]: id(li), id(li1), id(li2)
Out[23]: (40891600, 40878592, 40865016)

In [24]: id(li[-1]), id(li1[-1]), id(li2[-1])
Out[24]: (40906264, 40906264, 40906264)

3.深拷貝: 裏面的所有對象重新拷貝, 包括子對象;

In [25]: li3 = copy.deepcopy(li)

In [26]: id(li[-1]), id(li1[-1]), id(li3[-1])
Out[26]: (40906264, 40906264, 40879960)

元組(tuple)
1.元組創建
可以把元組看作一個容器,任何數據類型都可以放在這個容器裏面;
通過賦值方式創建元組

In [27]: t = (1, 1.0, 2j, True, (1,2,3))
In [28]: print t
(1, 1.0, 2j, True, (1, 2, 3))

 定義單個元組,一定要在這個元素後面加逗號

In [29]: t1 = (1,)
In [30]: print type(t1)
<type ‘tuple‘>

通過工廠方法創建元組

In [31]: t = tuple()

In [32]: print type(t)
<type ‘tuple‘>

2.元組的操作
索引
切片
連接
重復
成員操作符

`In [33]: t = (1, 1.0, 1L, 1+2j, ‘hello‘, [1,2])`
正向索引與反向索引以及元組嵌套時元素的訪問

In [34]: print t[0], t[-1], t[-1][-1]
1 [1, 2] 2

逆轉元組元素

In [35]: print t[::-1]
([1, 2], ‘hello‘, (1+2j), 1L, 1.0, 1)

連接

In [36]: print t+(1,2,3)
(1, 1.0, 1L, (1+2j), ‘hello‘, [1, 2], 1, 2, 3)


重復

In [37]: print t * 3
(1, 1.0, 1L, (1+2j), ‘hello‘, [1, 2], 1, 1.0, 1L, (1+2j), ‘hello‘, [1, 2], 1, 1.0, 1L, (1+2j), ‘hello‘, [1, 2])

成員操作符

In [38]: print 1 in t, 1 not in t
True False


3.元組是可叠代數據類型

In [41]: allow_ips = (‘172.25.254.1‘, ‘172.25.254.12‘, ‘172.25.254.13‘)
In [42]: for ip in allow_ips:
....: print ip
....:
172.25.254.1
172.25.254.12
172.25.254.13

測試練習:端口掃描器雛形
掃描172.25.254.0/24 這個網絡所有主機的ftp, ssh, http, mariadb, samba(21, 22, 80, 3306,3020)

ips = []

for i in range(1, 255):

ip = ‘172.25.254.‘+str(i)

ips.append(‘172.25.254.‘ + str(i))

ports = (21, 22, 80, 3306, 3020)

for ip in ips:
for port in ports:
print ‘[+] Scanning %s:%d‘ % (ip, port)

4.元組方法
count 統計次數

In [43]: t.count(1)
Out[43]: 3

index 顯示索引 

In [44]: t.index(1)
Out[44]: 0

元組變量交換
python 中後面如果詩歌表達式  從右往左算
x,y= (2,1) #先計算右邊的表達式y,x,在內存中開辟內存空間,生成元組(y,x):
x,y = y,x  #將x,y = (2,1) 
print x,y
元組是不可變數據類型

字典
1.字典創建
字典的簡單版定義1:

d = {

:前面的稱為鍵,key

#:後面的稱為值,value
#鍵值對(key-value)
‘name‘: ‘root‘,
‘passwd‘:‘westos‘

}
print d[‘name‘]
print d[‘passwd‘]


字典的升級版定義:

info = {
‘root‘:{
‘name‘: ‘root‘,
‘passwd‘:‘westos‘,
‘age‘:18,
‘eamil‘:[‘[email protected]‘, ‘[email protected]‘]
},

‘student‘: {
    ‘name‘: ‘student‘,
    ‘passwd‘: ‘westos‘,
    ‘age‘: 18,
    ‘eamil‘: [‘[email protected]‘, ‘[email protected]‘]
},

}

print info[‘root‘]


 通過工廠函數創建字典

d = dict()
print type(d)

d = dict(a=1, b=2, c=3)
print d, type(d)


fromkeys方法創建字典
d = {}.fromkeys([‘user1‘, ‘user2‘, ‘user3‘])
print d

![](http://i2.51cto.com/images/blog/201803/26/7c2ea2a8bd710344c1aacda79373e5eb.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

測試練習:
批量生成卡號並初始化密碼
要求描述:
1.生成銀行卡號, 前5位為:61021 後面4位: 1~1000
2.並給每個銀行卡初始化密碼為666666
3. 每5個為一行

cardids = []

for i in range(1, 1001):
cardid = "61021%.4d" % (i)
cardids.append((cardid))

cardInfo = {}.fromkeys(cardids, ‘666666‘)
#print len(cardInfo)
for i, j in enumerate(cardInfo):

if i % 5 == 0:
    print
print  j,
測試結果:
![](http://i2.51cto.com/images/blog/201803/26/d1885af95cc9532d3db6b5e9933e242e.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

2.字典的特性
不可行的特性: 索引, 切片, 連接, 重復,   (因為dict是無序的數據類型;)
可行的特性: 成員操作符
3.字典操作
字典值增加
update(key=value, .....)
   - 如果key值存在, 更新該key對應的value值;
   - 如果key不存在, 添加key-value值;

In [1]: d = dict(a=1, b=2)

In [2]: d
Out[2]: {‘a‘: 1, ‘b‘: 2}

In [3]: d.update(c=5,d=6)

In [4]: d
Out[4]: {‘a‘: 1, ‘b‘: 2, ‘c‘: 5, ‘d‘: 6}

In [5]: d.update(a=10,d=100,f=9)

In [6]: d
Out[6]: {‘a‘: 10, ‘b‘: 2, ‘c‘: 5, ‘d‘: 100, ‘f‘: 9}

setdefault(key,value)
 - 如果key值存在, 不操作;
 - 如果key不存在, 添加key-value值;

In [1]: d = dict(a=1, b= 2)

In [2]: d.setdefault(‘a‘, 10)
Out[2]: 1

In [3]: d
Out[3]: {‘a‘: 1, ‘b‘: 2}

In [4]: d.setdefault(‘f‘, 10)
Out[4]: 10

In [5]: d
Out[5]: {‘a‘: 1, ‘b‘: 2, ‘f‘: 10}


字典值查看

In [6]: d.keys() #查詢key值
Out[6]: [‘a‘, ‘b‘, ‘f‘]

In [7]: d.values() #查詢values值
Out[7]: [1, 2, 10]

In [8]: d.items() #查詢鍵值對
Out[8]: [(‘a‘, 1), (‘b‘, 2), (‘f‘, 10)]
In [9]: for i,j in d.items():
...: print i,j
...:
a 1
b 2
f 10

In [10]: d.has_key(‘a‘) #查詢字典裏是否含有‘a’這個key值
Out[10]: True

字典刪除
 pop(k[,d]):
- 如果key存在, 刪除key-value;
- 如果key不存在,判斷d是否存在:
 - 如果d不存在, 報錯KeyError;
 - 如果d存在, 返回d;

In [11]: d
Out[11]: {‘a‘: 1, ‘b‘: 2, ‘f‘: 10}

In [12]: d.pop(‘e‘, 1)
Out[12]: 1

In [13]: d.pop(‘a‘)
Out[13]: 1

In [14]: d
Out[14]: {‘b‘: 2, ‘f‘: 10}

In [15]: d.pop(‘b‘, 10)
Out[15]: 2

popitem():隨機刪除key-value對;當字典為空時報錯;

In [19]: d
Out[19]: {‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘f‘: 10}

In [20]: d.popitem()
Out[20]: (‘a‘, 1)

In [21]: d
Out[21]: {‘b‘: 2, ‘c‘: 3, ‘f‘: 10}

In [22]: del d[‘c‘]

In [23]: d
Out[23]: {‘b‘: 2, ‘f‘: 10}

In [24]: del d[‘c‘]

KeyError Traceback (most recent call last)
<ipython-input-24-975cd7d7076f> in <module>()
----> 1 del d[‘c‘]

KeyError: ‘c‘
In [34]: d.clear() #刪除字典裏所有元素

In [35]: d
Out[35]: {}

In [36]: del d #刪除整個字典


利用if語句實現switch(實現四則運算)

#!/usr/bin/env python
#coding:utf-8
from future import division

while 1:
num1 = input(‘Num1:‘)
oper = raw_input(‘操作符:‘)
num2 = input(‘Num2:‘)

if oper == "+":
    print  num1 +num2
elif oper == ‘-‘:
    print  num1 - num2
elif oper == ‘/‘:
    print  num1 / num2
elif oper == ‘*‘:
    print  num1 * num2
else:
    print ‘error‘
測試結果:
![](http://i2.51cto.com/images/blog/201803/26/11853b8377d329c7a2fd22a3f3851569.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

利用字典與函數實現switch(實現四則運算)

#!/usr/bin/env python
#coding:utf-8
from future import division

num1 = input(‘Num1:‘)
oper = raw_input(‘操作符:‘)
num2 = input(‘Num2:‘)

def add(num1, num2):
return num1 + num2

def div(num1, num2):
if num2 == 0:
raise IOError
else:
return num1 / num2

d = {
‘+‘: add,
‘-‘: num1 - num2,
‘: num1 num2,
‘/‘: div,
}

if oper in d:
print d[oper](num1, num2)
else:
print ‘error‘


測試結果:
![](http://i2.51cto.com/images/blog/201803/26/6492a6613209fd1870562b76426ebc3d.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

字典遍歷

#!/usr/bin/env python
#coding:utf-8

favourite_places = {
‘lee‘: [‘xian‘, ‘hangzhou‘],
‘fentiao‘:[‘hanzhong‘, ‘xianyang‘]
}

for name in favourite_places:
print "\n" + name.title() + "‘s favourite place are:"
for place in favourite_places[name]:
print place


測試結果:
![](http://i2.51cto.com/images/blog/201803/26/a7e27f86f13291ea930275d8a4ef16b6.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

集合:
集合是不重復的數據類型;字典中的key值不能重復;
In [37]: s = {1, 2, 3, 4, 1, 2}

In [38]: s
Out[38]: {1, 2, 3, 4}

列表去重
方法一:可以轉換為集合

In [39]: li = [1, 2, 3, 4, 1, 2, 4]

In [40]: list(set(li))
Out[40]: [1, 2, 3, 4]
方法二:轉化為字典,拿出所有的key; 註意: dict()不能直接將列表轉化為字典;
In [41]: {}.fromkeys(li).keys()
Out[41]: [1, 2, 3, 4]
定義集合
定義一個空集合
In [44]: s1 = set()

In [45]: type(s1)
Out[45]: set
字典可以轉化為集合
In [46]: d = dict(a=1, b=2, c=3)

In [47]: set(d)
Out[47]: {‘a‘, ‘b‘, ‘c‘}
 集合是無序的數據類型;
In [48]: s = {91, 2, 3, 12, 89}

In [49]: s.add(13)

In [50]: print s
set([2, 3, 12, 13, 89, 91])
集合不支持的特性: 索引, 切片, 重復,連接
集合支持的特性: 成員操作符
集合是可叠代的對象, 因此支持for循環遍歷元素;
In [51]: s = {91, 2, 3, 12, 89}

In [52]: for i in s:
   ....:     print i
   ....:     
91
89
2
3
12
集合的增刪查改
增加
In [53]: s = {1, 2, 3}

In [54]: s.add(4)

In [55]: s.update({3,4,5,6})

In [56]: s.update(‘hello‘)

In [57]: s.update([1,2,37,10])

In [58]: s
Out[58]: {1, 2, 3, 4, 5, 6, 10, 37, ‘e‘, ‘h‘, ‘l‘, ‘o‘}
刪除
In [68]: s1.pop()
Out[68]: 1

In [69]: s1
Out[69]: {3, 4, 5}
In [74]: s1.remove(5)

In [75]: s1
Out[75]: {4}
In [78]: s1.discard(4)

In [79]: s1
Out[79]: set()

集合的交,補差集
In [3]: s1 = {1, 2, 3, 4}

In [4]: s2 = {1, 2, 4, 5}
#交集
In [5]: s1 & s2
Out[5]: {1, 2, 4}
#補集
In [6]: s1 |  s2
Out[6]: {1, 2, 3, 4, 5}
#差集
In [7]: s1 -  s2
Out[7]: {3}

python元組 字典 集合