Python從基礎到精通day5

列表和元組 、 字典 、 集合

列表

  • 屬於容器、可變、順序類型
>>> from random import randint
>>> l1 = [randint(1, 100) for i in range(10)]
>>> l1
[47, 95, 14, 21, 28, 80, 23, 98, 17, 37]
>>> l1[0] = 80
>>> l1[2:4] = [10,50,20,80]
>>> l1
[80, 95, 10, 50, 20, 80, 28, 80, 23, 98, 17, 37]
  • 列表方法
>>> l1.append(80)     # 追加元素
>>> l1.insert(0, 20)  # 在下標爲0的位置插入20
>>> l1.extend([10, 20, 30])  # 向列表尾部增加3項
>>> l1.append([10, 20, 30])  # 向列表尾部增加1個列表
>>> l1.pop()          # 默認將列表最後一項彈出
>>> l1.index(98)      # 返回數據項98的下標
>>> l1.pop(10)        # 彈出下標爲10的數據項
>>> l1.remove(20)     # 刪除數據項20的第一次出現
>>> l1.sort()         # 排序
>>> l1.reverse()      # 翻轉
>>> l1.count(80)      # 統計80出現的次數
>>> l2 = l1           # l1和l2指向相同內存空間
>>> l2
[95, 80, 80, 80, 80, 50, 37, 30, 28, 23, 20, 20, 17, 10, 10]
>>> while 80 in l2:   # 刪除所有的80
...   l2.remove(80)
>>> l2
[95, 50, 37, 30, 28, 23, 20, 20, 17, 10, 10]
>>> l1                # l1與l2指向相同空間,所以也沒有80了
[95, 50, 37, 30, 28, 23, 20, 20, 17, 10, 10]
>>> l3 = l1.copy()    # 將l1的內容賦值給l3
>>> l1.clear()        # 清空列表
>>> l3                # l3並未清空
[95, 50, 37, 30, 28, 23, 20, 20, 17, 10, 10]

元組

  • 屬於容器、不可變、順序類型
  • 元組相當於是不可變的列表
>>> t1 = (10, 20, 30, 20, 100)
>>> t1.count(20)   # 統計20出現的次數
2
>>> t1.index(30)   # 返回30的下標
2
  • 單元素元組必須在最後有一個逗號
>>> t2 = (10)
>>> type(t2)
<class 'int'>
>>> t2
10
>>> t3 = (10,)
>>> type(t3)
<class 'tuple'>
>>> t3
(10,)
>>> len(t3)
1

練習1:列表模擬棧結構

#!/uer/bin/env python3
stack = []  首先定義一個存儲數據的列表
def push_it():
    data = input('數據:').strip()  strip去除字符串兩端空格
    if not data:
        print('格式錯誤,請重新嘗試')
    stack.append(data)

def pop_it():
    def pop_it():
    if [] == stack:
        print('空')
    else:
		print('從棧中彈出了% s' % stack.pop())

def view_it():
    print(stack)

def menu_it():
    promat = """(0)壓棧
(1)出棧
(2)查詢
(3)退出
請選擇(0/1/2/3)"""
    while 1:
     show_menu():
    "用於在屏幕上打印菜單,根據用戶選擇調用相關函數"
    # 將函數保存到字典中。注意函數名不要加引號,因爲加引號表示字符串,不是函數名
    # 函數名後面不要加()。因爲加(),表示函數調用,將函數結果保存到字典

        dic = {'0':push_it,'1':pop_it,'2':view_it} 定義一個字典用來調用函數
        xz = input(promat).strip()
        if xz not in ['0','1','2','3']:
            print('格式錯誤,請重試')
            return
        if xz == '3':
            print('bye','bye')
            break
        # elif xz == '2':
        #     view_it()
        # elif xz == '3':
        #     print('%s %s' %('bye','bye'))
        #     break
        dic[xz]()  通過字典的key來獲取value。



if __name__ == '__main__':
    menu_it()

字典

  • 屬於容器、可變、映射類型
  • 字典的key不能重複
  • 通過key進行賦值時,如果key已在字典中則修改值;如果key不在字典中,則新增值
  • 字典的key,必須是不可變類型
>>> d1 = {'name': 'tom', 'name': 'bob'}
>>> d1
{'name': 'bob'}
>>> d1['name'] = 'jerry'
>>> d1
{'name': 'jerry'}
>>> d1['age'] = 20
>>> d1
{'name': 'jerry', 'age': 20}
>>> d1[(100, 200)] = 'home'
>>> d1
{'name': 'jerry', 'age': 20, (100, 200): 'home'}
>>> d1[[100, 200]] = 'home'  # 報錯,key不能是可變對象
>>> len(d1)
3
>>> 20 in d1    # 20是字典的key嗎?
False
>>> 'age' in d1
True
>>> d1[0]       # 字典沒有順序,如果沒有名爲0的key則報錯

# 通過dict函數創建字典
>>> d2 = dict([('name', 'tom'), ('qq', '12345243'), ('email', '[email protected]')])
>>> d2
{'name': 'tom', 'qq': '12345243', 'email': '[email protected]'}
>>> d3 = {}.fromkeys(['tom', 'jerry', 'bob', 'alice'], 20)
>>> d3
{'tom': 20, 'jerry': 20, 'bob': 20, 'alice': 20}

# 遍歷字典
>>> for k in d2:
...   print(k, d2[k])

# 字典的clear和copy方法與列表完全一樣
# 字典的get方法是最常用的方法 
>>> d2.get('name')   # 取出key爲name的值
'tom'
# 如果key不存在,默認返回None
>>> print(d2.get('phone'))
None
# 如果key不存在,也可以返回指定的值
>>> print(d2.get('phone', 'not found'))
not found
>>> print(d2.get('email', 'not found'))
tom@tedu.cn

>>> d2.keys()    # 取出所有的key
dict_keys(['name', 'qq', 'email'])
>>> list(d2.keys())
['name', 'qq', 'email']
>>> d2.values()  # 取出所有的values
dict_values(['tom', '12345243', '[email protected]'])
>>> list(d2.items())  # 取出所有的(key, val)
[('name', 'tom'), ('qq', '12345243'), ('email', '[email protected]')]
>>> d2.pop('qq')  # 彈出key爲qq的項目
'12345243'
>>> d2.update({'city': 'shenzhen', 'age': 20})
>>> d2
{'name': 'tom', 'email': '[email protected]', 'city': 'shenzhen', 'age': 20}

練習2:字典使用的練習

import getpass
users = {} #定義一個字典用來存儲
def register():
    user = input('請輸入用戶名:').strip()
    if user in users:
        print('\033[32m;1m用戶以存在\033[0m')
    elif not user:
        print('\033[32;1m用戶名不能爲空\033[0m')
    else:
        password = getpass.getpass('密碼:')
        users[user]=password   #字典裏沒有這個key則創建key和value
        print('\033[32;1m註冊成功\033[0m')

def login():
    username  = input('用戶名:')
    password = getpass.getpass('密碼:')
    # if username in users and users[username] == password:
    if users.get(username) == password:     #判斷字典裏是否有輸入的用戶名。
        print('\033[32;1mLogin sussfull\033[0m')
        break
    else:
        print('\033[31;1mLogin error\033[0m')


def show_menu():
    promat = """(1)註冊:
(2)登陸:
(3)退出
請選擇(0/1/2):"""
    funs = {'1':register,'2':login}
    while 1:
        xz = input(promat).strip()
        if xz  not in {'1','2','3'}:
            print('格式錯誤')
            continue

        if xz == '3':
            print('Bye...')
            break

        funs[xz]()

if __name__ == '__main__':
    show_menu()

測試運行

[root@python day5]# python3 lianxi.py 
(1)註冊:
(2)登陸:
(3)退出
請選擇(0/1/2):1
請輸入用戶名:wenhao
密碼: 此處不顯示密碼是因爲調用了getpass.getpass
註冊成功
(1)註冊:
(2)登陸:
(3)退出
請選擇(0/1/2):2
用戶名:bob
密碼: 
Login error
(1)註冊:
(2)登陸:
(3)退出
請選擇(0/1/2):2
用戶名:wenhao
密碼:
Login sussfull
(1)註冊:
(2)登陸:
(3)退出
請選擇(0/1/2):3
Bye...

集合

  • 數學上,集合set是由不同元素構成的
  • 集合中數據,被稱作集合元素。集合元素都是不可變對象。
  • 集合沒有順序
  • 集合就像是一個無值的字典
  • 集合分成可變集合set,和不可變集合frozenset
>>> s1 = {10, 20, 30, 'abc', 'tom', 'jerry'}
>>> type(s1)
<class 'set'>
>>> s1
{10, 'jerry', 'abc', 20, 'tom', 30}
>>> s2 = set([10, 20, 30, 40, 50])
>>> s2
{40, 10, 50, 20, 30}
>>> s3 = set('abc')
>>> s4 = set('bcd')
>>> s3
{'c', 'b', 'a'}
>>> s4
{'d', 'c', 'b'}

>>> len(s2)
5
>>> for i in s2:
...   print(i)
>>> 20 in s2
True
>>> 100 not in s2
True


>>> s3 & s4   # 交集
{'c', 'b'}
>>> s3 | s4   # 並集
{'d', 'c', 'b', 'a'}
>>> s3 - s4   # 差補,s3中有,s4中沒有的是哪些
{'a'}
>>> s4 - s3
{'d'}
  • 集合方法
>>> s2.add(100)   # 添加元素
>>> s2.pop()      # 彈出一個元素
100
>>> s2.remove(50) # 移除50
>>> s3.union(s4)  # s3 | s4 s3和s4所有的都列出來
{'d', 'c', 'b', 'a'}
>>> s3.intersection(s4)  # s3 & s4;s3和s4都有的是哪些
{'c', 'b'}
>>> s3.difference(s4)    # s3 - s4  s3中有s4中沒有的
{'a'}
>>> s5 = s3.union(s4)
>>> s3.issubset(s5)      # s3是s5的子集嗎?
True
>>> s5.issuperset(s3)    # s5是s3的超集嗎?
True
  • 集合天然可以去重複
>>> from random import randint
>>> nums = [randint(1, 50) for i in range(20)]
>>> nums
[36, 41, 6, 44, 45, 30, 48, 20, 45, 50, 25, 28, 39, 20, 14, 22, 24, 4, 18, 44]
>>> set(nums)
{36, 4, 6, 39, 41, 44, 45, 14, 48, 50, 18, 20, 22, 24, 25, 28, 30}
>>> list(set(nums))
[36, 4, 6, 39, 41, 44, 45, 14, 48, 50, 18, 20, 22, 24, 25, 28, 30]

# 沒有集合的情況下,手工去重
>>> result = []
>>> for i in nums:
...   if i not in result:
...     result.append(i)

練習3:找到mima中有passwd中沒有的行

[root@localhost day05]# cp /etc/passwd /tmp/
[root@localhost day05]# cp /etc/passwd /tmp/mima
# 修改mima,使之與passwd不一樣
[root@localhost day05]# vim /tmp/mima
>>> with open('/tmp/mima') as f1:
...   s1 = set(f1)
>>> with open('/tmp/passwd') as f2:
...   s2 = set(f2)
>>> s3 = s1 - s2
>>> s3
{'how are you?\n', 'hello world!\n'}
>>> with open('/tmp/result.txt', 'w') as f3:
...   f3.writelines(s3)
[root@localhost day05]# cat /tmp/result.txt 
how are you?
hello world!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章