Day2 python基礎
阿新 • • 發佈:2018-02-22
err 完全 ice join find -- pycha 基礎 商家 一、列表
列表是我們最以後最常用的數據類型之一,通過列表可以對數據實現最方便的存儲、修改等操作
定義列表
names = ["ZhangYang", "Guyun", "Xiangpeng", "XuLiangChen"]
根據下標取值,下標從0開始
print(names)
print(names[0], names[2])
運行結果:
[‘ZhangYang‘, ‘Guyun‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
ZhangYang Xiangpeng
切片取值
print(names[1:3]) # 切片,取下標1和下標3之間的值,包括1但不包括3 print(names[3]) # 切片,取下標3的值 print(names[-2]) # 切片,取倒數第2個值 print(names[-2:]) # 切片,取列表最後2個值 print(names[0:3]) # 切片,取列表前3個值 print(names[:3]) # 切片,前邊是0的,可以忽略 運行結果 [‘Guyun‘, ‘Xiangpeng‘] XuLiangChen Xiangpeng [‘Xiangpeng‘, ‘XuLiangChen‘] [‘ZhangYang‘, ‘Guyun‘, ‘Xiangpeng‘] [‘ZhangYang‘, ‘Guyun‘, ‘Xiangpeng‘]
列表追加
names = ["ZhangYang", "Guyun", "Xiangpeng", "XuLiangChen"]
names.append("Leihaidong") # 最後追加
print(names)
運行結果
[‘ZhangYang‘, ‘Guyun‘, ‘Xiangpeng‘, ‘XuLiangChen‘, ‘Leihaidong‘]
指定下標插入
names = ["ZhangYang", "Guyun", "Xiangpeng", "XuLiangChen"] names.insert(1, "Chenronghua") # 指定位置插入 names.insert(3, "Xinzhiyu") print(names) 運行結果 [‘ZhangYang‘, ‘Chenronghua‘, ‘Guyun‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
替換列表值
names=[‘ZhangYang‘, ‘Chenronghua‘, ‘Guyun‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
names[2] = "Xiedi" #指定下標替換
運行結果
[‘ZhangYang‘, ‘Chenronghua‘, ‘Xiedi‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
刪除列表值
names=[‘ZhangYang‘, ‘Chenronghua‘, ‘Guyun‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘] names.remove("Chenronghua") #刪除指定的內容 print(names) 運行結果 [‘ZhangYang‘, ‘Guyun‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
names=[‘ZhangYang‘, ‘Chenronghua‘, ‘Guyun‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
del names[1] #根據下標刪除
print(names)
運行結果
[‘ZhangYang‘, ‘Guyun‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
names=[‘ZhangYang‘, ‘Chenronghua‘, ‘Guyun‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
names.pop(1) #刪除最後一個
print(names)
運行結果
[‘ZhangYang‘, ‘Guyun‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
查找元素位置
names=[‘ZhangYang‘, ‘Chenronghua‘, ‘Xiedi‘, ‘Xinzhiyu‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
print(names.index(‘Xiedi‘))
運行結果:
2
統計重復的元素個數
names=[‘ZhangYang‘, ‘Chenronghua‘, ‘Xiedi‘, ‘Xinzhiyu‘,‘Chenronghua‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
print(names.count(‘Chenronghua‘))
運行結果:
2
反轉列表
names=[‘ZhangYang‘, ‘Chenronghua‘, ‘Xiedi‘, ‘Xinzhiyu‘,‘Chenronghua‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
print(names)
names.reverse()
print(names)
運行結果:
[‘ZhangYang‘, ‘Chenronghua‘, ‘Xiedi‘, ‘Xinzhiyu‘, ‘Chenronghua‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
[‘XuLiangChen‘, ‘Xiangpeng‘, ‘Chenronghua‘, ‘Xinzhiyu‘, ‘Xiedi‘, ‘Chenronghua‘, ‘ZhangYang‘]
列表排序(默認按照ASCII碼排序):
names = ["4ZhangYang", "#!Guyun", "Xiangpeng","Chenronghua", "XuLiangChen"]
names.sort()
print(names)
運行結果:
[‘#!Guyun‘, ‘4ZhangYang‘, ‘Chenronghua‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
列表擴展
names=[‘ZhangYang‘, ‘Chenronghua‘, ‘Xiedi‘, ‘Xinzhiyu‘,‘Chenronghua‘, ‘Xiangpeng‘, ‘XuLiangChen‘]
names2=[1, 2, 3, 4]
print(names)
運行結果:
[‘ZhangYang‘, ‘Chenronghua‘, ‘Xiedi‘, ‘Xinzhiyu‘, ‘Chenronghua‘, ‘Xiangpeng‘, ‘XuLiangChen‘, 1, 2, 3, 4]
刪除列表
names2 = [1, 2, 3, 4]
del names2
print(names2)
運行結果:
Traceback (most recent call last):
File "/Users/erick/PycharmProjects/oldboy_python/day2/names.py", line 45, in <module>
print(names2)
NameError: name ‘names2‘ is not defined
淺copy列表(只拷貝列表第一層的內存地址,當原列表第二層的元素發生改變時,新列表會跟著改變)
names = ["4ZhangYang", "#!Guyun", "xXiangpeng", ["alex", "jack"], "Chenronghua", "XuLiangChen"]
names2 = names.copy()
print(names)
print(names2)
names[2] = "向鵬"
print(names)
print(names2)
names[3][0] = "ALEXANDER"
print(names)
print(names2)
運行結果
[‘4ZhangYang‘, ‘#!Guyun‘, ‘xXiangpeng‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘xXiangpeng‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘向鵬‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘xXiangpeng‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘向鵬‘, [‘ALEXANDER‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘xXiangpeng‘, [‘ALEXANDER‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
深度copy(完全克隆)
import copy
names = ["4ZhangYang", "#!Guyun", "xXiangpeng", ["alex", "jack"], "Chenronghua", "XuLiangChen"]
# names2 = names.copy()
names2 = copy.deepcopy(names)
print(names)
print(names2)
names[2] = "向鵬"
print(names)
print(names2)
names[3][0] = "ALEXANDER"
print(names)
print(names2)
運行結果:
[‘4ZhangYang‘, ‘#!Guyun‘, ‘xXiangpeng‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘xXiangpeng‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘向鵬‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘xXiangpeng‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘向鵬‘, [‘ALEXANDER‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
[‘4ZhangYang‘, ‘#!Guyun‘, ‘xXiangpeng‘, [‘alex‘, ‘jack‘], ‘Chenronghua‘, ‘XuLiangChen‘]
列表循環
names = ["4ZhangYang", "#!Guyun", "xXiangpeng", ["alex", "jack"], "Chenronghua", "XuLiangChen"]
for i in names:
print(i)
運行結果:
4ZhangYang
#!Guyun
xXiangpeng
[‘alex‘, ‘jack‘]
Chenronghua
XuLiangChen
二、元組
元組其實跟列表差不多,也是存一組數,只不是它一旦創建,便不能再修改,所以又叫只讀列表
語法
names = ("alex","jack","eric")
它只有2個方法,一個是count,一個是index
三、程序練習
購物車程序
需求:
- 啟動程序後,讓用戶輸入工資,然後打印商品列表
- 允許用戶根據商品編號購買商品
- 用戶選擇商品後,檢測余額是否夠,夠就直接扣款,不夠就提醒
- 可隨時退出,退出時,打印已購商品和余額
product_list = [
(‘Iphone‘, 5800),
(‘Mac Pro‘, 9800),
(‘Bike‘, 800),
(‘Watch‘, 10600),
(‘Coffee‘, 31),
(‘Alex Python‘, 120)
]
shopping_list = []
salary = input("Input your salary:")
if salary.isdigit():
salary = int(salary)
while True:
for index,item in enumerate(product_list):
#print(product_list.index(item),item)
print(index,item)
user_choice = input("選擇要買嘛?>>>:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0:
p_item = product_list[user_choice]
if p_item[1] <= salary: # 買的起
shopping_list.append(p_item)
salary -= p_item[1]
print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" %(p_item,salary))
else:
print("\033[41;1m你的余額只剩[%s]啦,還買個毛線\033[0m" % salary)
else:
print("product code [%s] is not exist!"% user_choice)
elif user_choice == ‘q‘:
print(‘--------shopping list---------‘)
for p in shopping_list:
print(p)
print("Your current balance:", salary)
exit()
else:
print("your input error!")
四、字符串操作
name = "my name is alex"
print(name.capitalize()) # 首字母大寫
print(name.count("a")) # 統計指定字符的個數
print(name.center(50,"-")) # 打印50個字符,不夠的用"-"補充,name字符串居中
print(name.endswith("ex")) # 判斷字符串以什麽結尾,匹配為True,不匹配為False
name = "my \tname is alex"
print(name.expandtabs(tabsize=30)) # 將\t轉換成多長的空格
print(name.find("name")) # 查找字符串位置
print(name[name.find("name"):9]) # 字符串切片
name = "my name is {name} and i am {year} old!"
print(name.format(name="alex", year=23)) # 傳遞參數內容
print(name.format_map({"name": "alex", "year": 23})) # 用字典的方式傳遞參數
print("abc123".isalnum()) # 阿拉伯數字和阿拉伯英文字符,英文字符以及0-9數字
print("abA".isalpha()) # 是否為阿拉伯英文字符
print("10".isdecimal()) # 是否為十進制
print("1".isdigit()) # 是否為整數
print("addd_d".isidentifier()) # 是否為合法的標誌符即變量名
print("aa".islower()) # 是否為小寫
print("34234".isnumeric()) # 是否都為純數字
print("My Name Is ".istitle()) # 判斷是否為title,即每單詞首字母大寫
print("My Name Is ".isprintable()) # 判斷能否打印,當是tty file或者drive file
print("My Name Is ".isupper()) # 判斷是否全為大寫
print("+".join([‘1‘, ‘2‘, ‘3‘])) # join成字符串
print(name.ljust(50, "*")) # 左對齊,長度50個字符,並用*補齊
print(name.rjust(50, "-")) # 右對齊,長度50個字符,並用-補齊
print("Alex".lower()) # 把大寫變成小寫
print("Alex".upper()) # 把小寫變成大寫
print("\n Alex".lstrip()) # 去除左側的空格或回車
print("Alex \n".rstrip()) # 去除右側的空格或回車
print("\n Alex \n".strip()) # 去除兩側的空格或回車
p = str.maketrans("abcdef", "123456") # 字符對應替換
print("alex li".translate(p))
print("alex li".replace(‘l‘, ‘L‘)) # 替換指定字符
print("alex li".replace(‘l‘, ‘L‘, 1)) # 替換1次
print("alex li".rfind(‘l‘)) # 從左往右查找,返回最右側的匹配字符的下標
print("al ex li".split()) # 切割,默認按照空格
print("al ex li".split(‘l‘)) # 按照字符"l"切割
print("al \nex li".splitlines()) # 按照換行符\n切割
print("Alex Li".swapcase()) # 大寫變小寫,小寫變大寫
print("alex li".title()) # 變成title即每個單詞的首字母大寫
print("alex li".zfill(50)) # 長度50,不夠用0左填充
運行結果:
My name is alex
2
-----------------my name is alex------------------
True
my name is alex
4
name
my name is alex and i am 23 old!
my name is alex and i am 23 old!
True
True
True
True
True
True
True
True
True
False
1+2+3
my name is {name} and i am {year} old!************
------------my name is {name} and i am {year} old!
alex
ALEX
Alex
Alex
Alex
1l5x li
aLex Li
aLex li
5
[‘al‘, ‘ex‘, ‘li‘]
[‘a‘, ‘ ex ‘, ‘i‘]
[‘al ‘, ‘ex li‘]
aLEX lI
Alex Li
0000000000000000000000000000000000000000000alex li
五、字典
字典一種key - value 的數據類型,使用就像我們上學用的字典,通過筆劃、字母來查對應頁的詳細內容。
修改以及增加
info = {
‘stu1101‘: "TengLan Wu",
‘stu1102‘: "LongZe Luola",
‘stu1103‘: "XiaoZe Maliya",
}
print(info)
print(info[‘stu1101‘])
info["stu1101"] = "武藤蘭" # 修改
print(info)
info["stu1104"] = "Cangjingkong" # 增加
print(info)
運行結果:
{‘stu1101‘: ‘TengLan Wu‘, ‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘}
TengLan Wu
{‘stu1101‘: ‘武藤蘭‘, ‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘}
{‘stu1101‘: ‘武藤蘭‘, ‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1104‘: ‘Cangjingkong‘}
刪除
info = {
‘stu1101‘: "TengLan Wu",
‘stu1102‘: "LongZe Luola",
‘stu1103‘: "XiaoZe Maliya",
‘stu1104‘: ‘Cangjingkong‘,
}
# del
# del info # 刪除字典
del info[‘stu1101‘] # 刪除元素
print(info)
info.pop("stu1102") # 刪除元素
print(info)
info.popitem() # 隨機刪除一個
print(info)
運行結果:
{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1104‘: ‘Cangjingkong‘}
{‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1104‘: ‘Cangjingkong‘}
{‘stu1103‘: ‘XiaoZe Maliya‘}
查找
info = {
‘stu1101‘: "TengLan Wu",
‘stu1102‘: "LongZe Luola",
‘stu1103‘: "XiaoZe Maliya",
}
# 查找
print(info.get(‘stu1103‘))
運行結果:
XiaoZe Maliya
多級字典嵌套
av_catalog = {
"歐美":{
"www.youporn.com": ["很多免費的,世界最大的","質量一般"],
"www.pornhub.com": ["很多免費的,也很大","質量比yourporn高點"],
"letmedothistoyou.com": ["多是自拍,高質量圖片很多","資源不多,更新慢"],
"x-art.com":["質量很高,真的很高","全部收費,屌比請繞過"]
},
"日韓":{
"tokyo-hot":["質量怎樣不清楚,個人已經不喜歡日韓範了","聽說是收費的"]
},
"大陸":{
"1024":["全部免費,真好,好人一生平安","服務器在國外,慢"]
}
}
av_catalog["大陸"]["1024"][1] = "可以在國內做鏡像"
print(av_catalog["大陸"]["1024"])
運行結果:
[‘全部免費,真好,好人一生平安‘, ‘可以在國內做鏡像‘]
打印keys和values
info = {
‘stu1101‘: "TengLan Wu",
‘stu1102‘: "LongZe Luola",
‘stu1103‘: "XiaoZe Maliya",
}
print(info.values()) # 打印key值
print(info.keys()) # 打印key
運行結果:
dict_values([‘TengLan Wu‘, ‘LongZe Luola‘, ‘XiaoZe Maliya‘])
dict_keys([‘stu1101‘, ‘stu1102‘, ‘stu1103‘])
setdefault
av_catalog = {
"歐美":{
"www.youporn.com": ["很多免費的,世界最大的","質量一般"],
"www.pornhub.com": ["很多免費的,也很大","質量比yourporn高點"],
"letmedothistoyou.com": ["多是自拍,高質量圖片很多","資源不多,更新慢"],
"x-art.com":["質量很高,真的很高","全部收費,屌比請繞過"]
},
"日韓":{
"tokyo-hot":["質量怎樣不清楚,個人已經不喜歡日韓範了","聽說是收費的"]
},
"大陸":{
"1024":["全部免費,真好,好人一生平安","服務器在國外,慢"]
}
print(av_catalog.setdefault("臺灣", {"www.baidu.com": [1, 2]})) # 如果能取到就返回這個值,取不到就創建新的
print(av_catalog)
print(av_catalog.setdefault("大陸", {"www.baidu.com": [1, 2]}))
print(av_catalog)
運行結果:
{‘www.baidu.com‘: [1, 2]}
{‘歐美‘: {‘www.youporn.com‘: [‘很多免費的,世界最大的‘, ‘質量一般‘], ‘www.pornhub.com‘: [‘很多免費的,也很大‘, ‘質量比yourporn高點‘], ‘letmedothistoyou.com‘: [‘多是自拍,高質量圖片很多‘, ‘資源不多,更新慢‘], ‘x-art.com‘: [‘質量很高,真的很高‘, ‘全部收費,屌比請繞過‘]}, ‘日韓‘: {‘tokyo-hot‘: [‘質量怎樣不清楚,個人已經不喜歡日韓範了‘, ‘聽說是收費的‘]}, ‘大陸‘: {‘1024‘: [‘全部免費,真好,好人一生平安‘, ‘服務器在國外,慢‘]}, ‘臺灣‘: {‘www.baidu.com‘: [1, 2]}}
{‘1024‘: [‘全部免費,真好,好人一生平安‘, ‘服務器在國外,慢‘]}
{‘歐美‘: {‘www.youporn.com‘: [‘很多免費的,世界最大的‘, ‘質量一般‘], ‘www.pornhub.com‘: [‘很多免費的,也很大‘, ‘質量比yourporn高點‘], ‘letmedothistoyou.com‘: [‘多是自拍,高質量圖片很多‘, ‘資源不多,更新慢‘], ‘x-art.com‘: [‘質量很高,真的很高‘, ‘全部收費,屌比請繞過‘]}, ‘日韓‘: {‘tokyo-hot‘: [‘質量怎樣不清楚,個人已經不喜歡日韓範了‘, ‘聽說是收費的‘]}, ‘大陸‘: {‘1024‘: [‘全部免費,真好,好人一生平安‘, ‘服務器在國外,慢‘]}, ‘臺灣‘: {‘www.baidu.com‘: [1, 2]}}
update
info = {
‘stu1101‘: "TengLan Wu",
‘stu1102‘: "LongZe Luola",
‘stu1103‘: "XiaoZe Maliya",
}
b = {
‘stu1101‘: "Alex",
1: 3,
2: 5
}
info.update(b) # 兩個字典合並,有交叉就更新,無交叉就創建
print(info)
運行結果:
{‘stu1101‘: ‘Alex‘, ‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, 1: 3, 2: 5}
items
info = {
‘stu1101‘: "TengLan Wu",
‘stu1102‘: "LongZe Luola",
‘stu1103‘: "XiaoZe Maliya",
}
print(info.items()) # 將字典轉換為列表
運行結果:
dict_items([(‘stu1101‘, ‘TengLan Wu‘), (‘stu1102‘, ‘LongZe Luola‘), (‘stu1103‘, ‘XiaoZe Maliya‘)])
fromkeys
c = dict.fromkeys([6,7,8],"test") # 初始化列表,參數列表為key,"test" 為默認key值
print(c)
運行結果:
{6: ‘test‘, 7: ‘test‘, 8: ‘test‘}
踩過的坑
d = dict.fromkeys([6,7,8],[1,{"name":"alex"},444]) # 註意多層,引用的是內存地址
print(d)
d[7][1]["name"] = "Jcak chen"
print(d)
運行結果:
{6: [1, {‘name‘: ‘alex‘}, 444], 7: [1, {‘name‘: ‘alex‘}, 444], 8: [1, {‘name‘: ‘alex‘}, 444]}
{6: [1, {‘name‘: ‘Jcak chen‘}, 444], 7: [1, {‘name‘: ‘Jcak chen‘}, 444], 8: [1, {‘name‘: ‘Jcak chen‘}, 444]}
循環字典
info = {
‘stu1101‘: "TengLan Wu",
‘stu1102‘: "LongZe Luola",
‘stu1103‘: "XiaoZe Maliya",
}
for i in info: # 更為高效,建議用這種
print(i,info[i])
for k,v in info.items(): # 先將字典轉換為列表
print(k,v)
六、三級菜單
實現:三級菜單打印,b返回上一級,q退出程序
data = {
"北京": {
"昌平":{
"沙河":["oldboy", "test"],
"天通苑":["鏈家地產", "我愛我家"]
},
"朝陽":{
"望京":["奔馳", "陌陌"],
"國貿":["CICC","HP"],
"東直門":["Adevetn","飛信"]
},
"海澱":{
},
},
"山東":{
"德州":{},
"青島":{},
"濟南":{}
},
"廣東":{
"東莞":{},
"常熟":{},
"佛山":{}
}
}
exit_flag = False
while not exit_flag:
for i in data:
print(i)
choice = input("選擇進入1>>:")
if choice in data:
while not exit_flag:
for i2 in data[choice]:
print("\t",i2)
choice2 = input("選擇進入2>>:")
if choice2 in data[choice]:
while not exit_flag:
for i3 in data[choice][choice2]:
print("\t\t",i3)
choice3 = input("請選擇進入3>>:")
if choice3 in data[choice][choice2]:
for i4 in data[choice][choice2][choice3]:
print("\t\t",i4)
choice4 = input("選擇進入4>>:")
if choice4 == "b":
pass
elif choice4 == "q":
exit_flag = True
if choice3 == "b":
break
elif choice3 == "q":
exit_flag = True
if choice2 == "b":
break
elif choice2 == "q":
exit_flag = True
作業
用戶入口
- 商品信息存在文件裏
- 已購商品,余額記錄
商家入口
- 可以添加商品
- 可以修改商品價格
Day2 python基礎