在前面我們已經介紹了變量的概念,變量可以存儲一個元素,而清單是一個 “大容器” ,可以存儲多個元素,這樣程式就可以友善地對這些資料進行整體操作。
1. 清單的建立
清單的建立有兩種方式:使用中括号或使用内置函數 list(),清單内各元素用逗号隔開。
# 使用[]建立清單
list1 = [1, 2, "michael"]
# 使用内置函數list()建立清單
list2 = list([23, "jackson", 2.3])
# 分别列印兩個清單的值、類型、id
print(list1, type(list1), id(list1))
print(list2, type(list2), id(list2))
# 輸出結果
[1, 2, 'michael'] <class 'list'> 1852624487872
[23, 'jackson', 2.3] <class 'list'> 1852624871552
2. 清單的特點
清單的特點:
1)清單元素按順序有序排列;
2)每一個索引對應唯一資料;
3)清單可以存儲重複資料;
4)清單可以存儲任意類型資料;
5)根據動态配置設定記憶體和回收記憶體。
# 清單元素按順序有序排列
'''清單定義的時候“hello”在第一個,列印輸出清單的時候“hello”也在第一個'''
list1 = ["hello", 123, "python"]
print(list1)
# 一個索引對應唯一值
print(list1[0], list1[1], list1[2])
# 清單可以存儲重複資料
list2 = ["hello", "hello", 12, 12]
print(list2)
# 清單可以存儲任意類型資料
list3 = ["hello", 12, 2.5, True]
print(list3)
# 輸出結果
['hello', 123, 'python']
hello 123 python
['hello', 'hello', 12, 12]
['hello', 12, 2.5, True]
3. 清單的增删改查
清單是 Python 中的可變序列,可以進行增删改查的操作。
'''向清單中添加元素'''
# 将a元素添加到清單末尾
append(a)
# 将L中的元素添加到清單中
extend(L)
# 在索引i處添加元素a
insert(i, a)
'''删除清單中的元素'''
# 删除清單中的a
remove(a)
# 删除并傳回清單中i的索引,預設-1
pop([i])
# 清空清單
clear()
# 删除清單
del()
'''查找元素'''
# 根據索引擷取元素
list[索引]
# 擷取清單多個元素
list[start: stop: step]
# 判斷元素a是否存在
a in list
a not in list
# 傳回清單中元素a的索引
index(a)
# 傳回清單中元素a出現的次數
count(a)
# 周遊清單的所有元素
for i in list:
'''修改清單元素'''
# 為指定索引的元素賦一個新的值
'''元素排序操作'''
# 逆序
reverse()
# 排序
Sort(key=None, reverse=True or False)
4. 清單生成式
清單生成式簡稱:生成清單的公式
# 文法格式
list1 = [i*i for i in range(1, 10)]
print(list1)
'''i*i是清單元素表達式;i是自定義變量;range(1, 10)為可疊代對象'''
# 輸出結果
[1, 4, 9, 16, 25, 36, 49, 64, 81]
5. 清單執行個體練習
例:編寫一個程式,在控制台輸出九九乘法表。
i = 1
j = 1
lists = []
while i < 10:
for j in range(1, j+1):
a = str(i) + "*" + str(j) + "=" + str(i*j) + " "
lists.append(a)
# 将清單轉化為字元串
print("".join(lists))
# print(lists)
# 清空清單
lists = []
j += 1
i += 1
# 輸出結果
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
例:編寫一個簡單的使用者登入系統
# 定義清單,記錄使用者資訊
users = ["123", "1234"]
passwords = ["123", "456"]
# 定義登入次數
try_count = 0
# 判斷登入次數是否超過3次,并循環
while try_count < 3:
# 登入操作
inuser = input("請輸入使用者名:")
inpassword = input("請輸入密碼:")
try_count += 1
if inuser in users:
# 找出使用者名的索引
index = users.index(inuser)
# 找出密碼的索引
password = passwords.index(inpassword)
# 判斷使用者名和密碼是否一緻
if index == password:
print(f"{inuser}登入成功")
break
else:
print(f'{inuser}登入失敗:密碼錯誤!')
else:
print(f"使用者{inuser}不存在,請建立使用者")
# 建立使用者
newuser = input("建立使用者名:")
newpassword1 = input("設定密碼:")
newpassword2 = input("再次輸入密碼:")
if newpassword1 == newpassword2:
# 将新建立的使用者添加到清單中
print(f"使用者{newuser}建立成功!")
users.append(newuser)
passwords.append(newpassword1)
print(users)
else:
print("兩次密碼不相同!")
continue
else:
print("登入已鎖定!")