1. 程式人生 > >python列表、元組與集合

python列表、元組與集合

python列表
一、列表的建立與操作
1.建立列表

a = []    ##元素型別可為int,float,complex,str,list,tuple
b = [a, 1, True, 3j + 2, "hi"]
c = [[1, 2, 3, 4], [a, b], 233, "hello"]
d = [a, b, c ,'0.1']
print(a)
print(b)
print(c)
print(d)


[]
[[], 1, True, (2+3j), 'hi']
[[1, 2, 3, 4], [[], [[], 1, True, (2+3j), 'hi']], 233, 'hello'
] [[], [[], 1, True, (2+3j), 'hi'], [[1, 2, 3, 4], [[], [[], 1, True, (2+3j), 'hi']], 233, 'hello'], '0.1']

2.列表的索引與切片:

c = [[1, 2, 3, 4], [5,6], 233, "hello"]
print(c)
print(type(c))    ##顯示型別
print(c[0][-1])
print(c[-1][3])
print(c[-2])


[[1, 2, 3, 4], [5, 6], 233, 'hello']
<class 'list'>
4 l 233

3.強制轉換

>>> s = list(range(5))  ##採用內建方法list()強制轉換
>>> s
[0, 1, 2, 3, 4]
>>> s[3]
3
>>> s[0]
0

4.列表的重複

>>> list = [1,2,3,'hello']
>>> list*3
[1, 2, 3, 'hello', 1, 2, 3, 'hello', 1, 2, 3, 'hello']

5.列表的成員操作符

>>> list
[1, 2
, 3, 'hello'] >>> 1 in list True >>> 'file' in list False

6.列表的連線

>>> list
[1, 2, 3, 'hello']
>>> list2 = ['file','westos']
>>> list+list2
[1, 2, 3, 'hello', 'file', 'westos']

二、列表的編輯
1.新增元素 append 和 extend
append:新增元素,預設新增到最後

>>> list = [1,2,3,4,5]
>>> list.append('f')
>>> print(list)
[1, 2, 3, 4, 5, 'f']

extend :將新列表元素全部新增

>>> nal=['hello','file']
>>> list.extend(nal)
>>> list
[1, 2, 3, 4, 5, 'f', 'hello', 'file']

如果用append新增列表,則:

>>> list.append(nal)    ```##將列表作為元素新增```
>>> list
[1, 2, 3, 4, 5, 'f', 'hello', 'file', ['hello', 'file']]

2.刪除 remove 、pop 和 del(可刪除列表) clear(清空列表)
remove:

>>> list.remove(1)
>>> list
[2, 3, 4, 5, 'f', 'hello', 'file', ['hello', 'file']]

pop:

>>> list
[2, 3, 4, 5, 'f', 'hello', 'file', ['hello', 'file']]
>>> list.pop(3)  ##刪除索引的元素,並返回索引值
5
>>> list
[2, 3, 4, 'f', 'hello', 'file', ['hello', 'file']]

del:

>>> list
[2, 3, 4, 'f', 'hello', 'file', ['hello', 'file']]
>>> del list[-1]    ##刪除指定元素
>>> list
[2, 3, 4, 'f', 'hello', 'file']
>>> del list[:-4]     ##除了最後4的元素全刪除
>>> list
[4, 'f', 'hello', 'file']
>>> del list[2:]     ##從第2個索引開始全刪除
>>> list
[4, 'f']

3.插入 insert

>>> list
[4, 'f']
>>> list.insert(1,'hello')  ##插入到索引值前
>>> list
[4, 'hello', 'f']

4.統計次數 count

>>> list
[4, 'hello', 'f']
>>> list.count('f')  ##統計f出現的次數
1

5.修改(重新賦值)

>>> list
[4, 'hello', 'f']
>>> list[1]='westos'  ##索引修改
>>> list
[4, 'westos', 'f']

6.索引 index

>>> list
[4, 'westos', 'f']
>>> list.index('f')  ##輸入元素
2                    ##輸出對應的索引值
>>> list.index('westos')
1

7.排序 sort

>>> a = ['w','e','f','g']
>>> a.sort()   ##正序,按ASCII碼大小排列
>>> a
['e', 'f', 'g', 'w']
>>> a.sort(reverse=True)   ##倒序,注意:reverse預設為False
>>> a
['w', 'g', 'f', 'e']
>>> a[::-1]   ##倒序
['e', 'f', 'g', 'w']

隨機排列

>>> import random
>>> a = [1,2,3,4,5,6]
>>> random.shuffle(a)
>>> a
[1, 4, 2, 6, 5, 3]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5, 6]

8.反轉 reverse

>>> a = ['s','d','f','g','h']
>>> a.reverse()
>>> a
['h', 'g', 'f', 'd', 's']

9.複製 copy

練習:將使用者列表與密碼列表一一匹配登陸,若使用者不存在、密碼錯誤則提示報錯;三次登陸機會!

while 1:
    user = ['root','student','westos','file','w']
    passwd = ['123','234','345','456','1128']
    for i in range(3):
        USER = input("請輸入使用者:")
        # c = input("請輸入密碼:")
        if USER in user:
            PASS = input("請輸入密碼:")
            d=user.index(USER)
            if PASS == passwd[d]:
                print("ok")
                break
            else:
                print("密碼不正確")
        else:
            print("沒有" + USER + "使用者")
    else:
        print("超過三次登陸!!")
        break


請輸入使用者:file
請輸入密碼:file
密碼不正確
請輸入使用者:hello
沒有hello使用者
請輸入使用者:westos
請輸入密碼:789
密碼不正確
超過三次登陸!!

注意:若密碼加密,需匯入getpass模組,且該模組只能在命令列執行!!

三、構建佇列與棧資料結構
1.簡單佇列結構構建(特點:先進先出)

queue = []
max_count = 10
menu = """
                    列隊操作
                1).入隊
                2).出隊
                3).隊頭
                4).隊尾
                5).佇列長度
                6).佇列元素顯示
                7).佇列是否為空
                8).佇列是否滿
請輸入你的選擇:"""
while 1:
    choice = input(menu)
    if choice == '1':
        print("入隊操作:".center(60, '*'))
        if len(queue) < 10:
            item = input("佇列元素:")
            queue.append(item)
            print("%s入隊成功" % (item))
        else:
            print("佇列以滿")
    elif choice == '2':
        if not queue:
            print("對列為空")
        else:
            print("出隊操作:".center(60, '*'))
            item = queue.pop(0)
            print("%s出隊成功" % (item))
    elif choice == '3':
        if not queue:
            print("對列為空")
        else:
            print(queue.index(0))
    elif choice == '4':
        if not queue:
            print("對列為空")
        else:
            print(queue.index(-1))
    elif choice == '5':
        if not queue:
            print("對列為空")
        else:
            print(len(queue))
    elif choice == '6':
        if not queue:
            print("對列為空")
        else:
            for i in queue:
                print(i, end=' ')
    elif choice == '7':
        if not queue:
            print("對列為空")
        else:
            print("對列不為空")
    elif choice == '8':
        if len(queue) == max_count:
            print("佇列以滿")
        else:
            print("佇列未滿"else:
        print("錯誤選擇")