程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

A week of quick start Python day02

編輯:Python


活動地址:CSDN21天學習挑戰賽

學習的最大理由是想擺脫平庸,早一天就多一份人生的精彩;遲一天就多一天平庸的困擾.各位小伙伴,如果您:
想系統/深入學習某技術知識點…
一個人摸索學習很難堅持,想組團高效學習…
想寫博客但無從下手,急需寫作干貨注入能量…
熱愛寫作,願意讓自己成為更好的人…


歡迎參與CSDN學習挑戰賽,成為更好的自己,請參考活動中各位優質專欄博主的免費高質量專欄資源(這部分優質資源是活動限時免費開放喔~),按照自身的學習領域和學習進度學習並記錄自己的學習過程.您可以從以下3個方面任選其一著手(不強制),或者按照自己的理解發布專欄學習作品,參考如下:

**

學習計劃

1,學習目標

提示:可以添加學習目標
例如: 一周掌握 Python 入門知識

2,學習內容

提示:可以添加要學的內容
例如:
A,掌握 Python 基本語法
B,掌握 Python 列表、字典、元組等集合類型的用法
C,掌握 Python 函數
D,掌握 Python 常用模塊
E, 掌握 Python 模塊與包
F,掌握 Python 類與對象

3,學習時間

每天拿出來兩個小時

4,學習產出

CSDN技術博客 每天一篇

學習日記

day02 Python的基礎語法——列表、字典、元組

1.List initial

name1 = "Zhang Xinxiao"
name2 = "潘磊"
# 列表的構建 語法格式 [數據對象,...,]
# 特點1: 列表中的元素可以是任意數據類型
# 特點2: 列表中的元素個數沒有限制
l1 = [100, "hello", True]
print(type(l1)) # list
l2 = [100, 2, 34, 5]
print(len(l2)) # 4
names = ["", "", "", ]

2.列表的序列操作

l = [10, 20, 30, 40, 50]
# A list is a sequence type
# 一 支持正負索引 數據對象[索引]
# print(l[1])
# print(l[-3])
print(id(l))
l[0] = 100
print(l)
print(id(l))
# 二 支持切片: 數據對象[開始索引:結束索引:步長] 顧頭不顧尾
# print(l[1:4]) # [20, 30, 40]
# print(l[-4:-1]) # [20, 30, 40]
# print(l[1:]) # [20, 30, 40, 50]
# print(l[:3]) # [20, 30, 40, 50]
# print(l[:]) # [10, 20, 30, 40, 50]
# print(l[-2:-5:-1]) # [40, 30, 20]
# 三 in操作: Whether a value is an element value in a list
# names = ["rain", "yuan", "alvin"]
# print("rai" in names)
# print("rai" in "rain")
# print(1 in ["1", 2, 3])
# # 案例
# n = 0
# while n < 100:
#
# # if n != 88 and n != 66:
# # print(n)
#
# if n not in [66, 88, 33, 44, 55]:
# print(n)
#
# n += 1
# 拼接 +
l1 = [1, 2, 3]
l2 = [4, 5, 6]
print(l1 + l2) # [1, 2, 3, 4, 5, 6]
print(l1)
print(l2)

3.列表內置方法

# 列表內置方法: 列表對象.方法()
# Lists have built-in methods for managing the data in the list:增刪改查
# 一 增:append:追加 insert:Insert a value anywhere extend
# print("hello".upper())
# 案例1: append
# l = [10, 20, 30, 40]
# ret = l.append(50)
# print(l) # [10, 20, 30, 40,50]
# print(ret) # None
# 案例2: insert(索引,值)
# l = [10, 20, 30, 40]
# l.insert(0, 100)
# print(l) # [100, 10, 20, 30, 40]
# 案例3: extend
# l1 = [10, 20, 30, [4, 5, 6]]
# 如何獲取5的值
# print(l1[3][1])
# print(len(l1))
# l2 = [1, 2, 3]
# l3 = [4, 5, 6]
# l2.append(l3)
# print(l2) # [1,2,3,[4,5,6]]
# print(len(l2))
# print(id(l2))
# ret = l2.extend(l3)
# print("ret:", ret)
# print(l2) # [1, 2, 3, 4, 5, 6]
# print(id(l2))
# 二 刪 pop():按索引刪除 remove():按值刪除 clear():清空
# names = ["張三", "李四", "王五"]
# 按索引刪除
# del_name = names.pop(0) # pop返回刪除元素值
# print(names)
# print("將%s刪除掉了" % del_name)
# 按元素值刪除
# ret = names.remove("李四")
# print(ret) # None
# print(names)
# 清空列表
# names.clear()
# print(names) # []
# del names
# print(names)
# 三 改: There is no built-in method to modify an element,It can only be done by indexing
# l = [1, 2, 3]
# l[0] = 100
# print(l) # [100, 2, 3]
# 四 查 index count sort reverse
# names = ["張三", "李四", "王五", "李四"]
# print(names.index("李四"))
# print(names.count("李四"))
#
# age_list = [20, 22, 18, 45, 32]
# # age_list.reverse() # age_list :[32,45,18,22,20]
#
# age_list.sort(reverse=True)
# print(age_list) # [45, 32, 22, 20, 18]
#
# age_list = ["100", "10", "12"]
# age_list.sort()
# print(age_list) # ['10', '100', '32']
# 練習題
# 將字符串 "20,15,34,188,26"All numbers in are sorted by largest to smallest"-"as a delimiter to form a new string
# 方案1:
# s = "20,15,34,188,26"
# l1 = s.split(",")
# print(l1) # ['20', '15', '34', '188', '26']
# l2 = []
# for i in l1:
# l2.append(int(i))
#
# print(l2)
# l2.sort(reverse=True)
# print(l2)
# l3 = []
# for i in l2: # l2: [15, 20, 26, 34, 188]
# l3.append(str(i))
# print(l3) # ['15', '20', '26', '34', '188']
#
# print("-".join(l3)) # 15-20-26-34-188
# 方案2
s = "20,15,34,188,26"
l1 = s.split(",") # ['20', '15', '34', '188', '26']
l2 = [int(i) for i in l1]
l2.sort(reverse=True)
l3 = [str(i) for i in l2]
print("-".join(l3)) # 188-34-26-20-15

4.Cyclic sum of listsrange函數

# 列表內置方法: 列表對象.方法()
# Lists have built-in methods for managing the data in the list:增刪改查
# 一 增:append:追加 insert:Insert a value anywhere extend
# print("hello".upper())
# 案例1: append
# l = [10, 20, 30, 40]
# ret = l.append(50)
# print(l) # [10, 20, 30, 40,50]
# print(ret) # None
# 案例2: insert(索引,值)
# l = [10, 20, 30, 40]
# l.insert(0, 100)
# print(l) # [100, 10, 20, 30, 40]
# 案例3: extend
# l1 = [10, 20, 30, [4, 5, 6]]
# 如何獲取5的值
# print(l1[3][1])
# print(len(l1))
# l2 = [1, 2, 3]
# l3 = [4, 5, 6]
# l2.append(l3)
# print(l2) # [1,2,3,[4,5,6]]
# print(len(l2))
# print(id(l2))
# ret = l2.extend(l3)
# print("ret:", ret)
# print(l2) # [1, 2, 3, 4, 5, 6]
# print(id(l2))
# 二 刪 pop():按索引刪除 remove():按值刪除 clear():清空
# names = ["張三", "李四", "王五"]
# 按索引刪除
# del_name = names.pop(0) # pop返回刪除元素值
# print(names)
# print("將%s刪除掉了" % del_name)
# 按元素值刪除
# ret = names.remove("李四")
# print(ret) # None
# print(names)
# 清空列表
# names.clear()
# print(names) # []
# del names
# print(names)
# 三 改: There is no built-in method to modify an element,It can only be done by indexing
# l = [1, 2, 3]
# l[0] = 100
# print(l) # [100, 2, 3]
# 四 查 index count sort reverse
# names = ["張三", "李四", "王五", "李四"]
# print(names.index("李四"))
# print(names.count("李四"))
#
# age_list = [20, 22, 18, 45, 32]
# # age_list.reverse() # age_list :[32,45,18,22,20]
#
# age_list.sort(reverse=True)
# print(age_list) # [45, 32, 22, 20, 18]
#
# age_list = ["100", "10", "12"]
# age_list.sort()
# print(age_list) # ['10', '100', '32']
# 練習題
# 將字符串 "20,15,34,188,26"All numbers in are sorted by largest to smallest"-"as a delimiter to form a new string
# 方案1:
# s = "20,15,34,188,26"
# l1 = s.split(",")
# print(l1) # ['20', '15', '34', '188', '26']
# l2 = []
# for i in l1:
# l2.append(int(i))
#
# print(l2)
# l2.sort(reverse=True)
# print(l2)
# l3 = []
# for i in l2: # l2: [15, 20, 26, 34, 188]
# l3.append(str(i))
# print(l3) # ['15', '20', '26', '34', '188']
#
# print("-".join(l3)) # 15-20-26-34-188
# 方案2
s = "20,15,34,188,26"
l1 = s.split(",") # ['20', '15', '34', '188', '26']
l2 = [int(i) for i in l1]
l2.sort(reverse=True)
l3 = [str(i) for i in l2]
print("-".join(l3)) # 188-34-26-20-15

5.列表推導式

# l = [1, 2, 3, 4, 5]
# l2 = []
# for i in l:
# l2.append(i * i)
# print(l2)
# 列表推導式:[表達式 for i in 可迭代對象]
l = [1, 2, 3, 4, 5]
l2 = [i * i for i in l]
print(l2) # [1,4,9,16,25]

6.Dictionary initial

# 字典是python的唯一一個hash映射的數據類型
l = ["rain", 22, "male"]
# A key-value pair in a dictionary is an element
# 字典的鍵必須是不可變數據類型(Except list and dictionary data types),Commonly used are strings and integers
# 字典的值可以是任意數據類型
# In principle, there are no restrictions on the key-value pairs of a dictionary
# 字典特點:無序,鍵不能重復
d = {
"name": "rain", "age": 22, "gender": "male"}
print(d, type(d)) # dict

7.字典的基本操作

stu = {
"name": "yuan", "age": 22}
# print(len(stu))
# 一 通過鍵查詢值 列表對象[索引] 字典對象[鍵]
print(stu["name"]) # yuan
print(stu["age"]) # yuan
print(stu["xxx"]) # 鍵不存在報錯
# 二 添加或修改
stu["gender"] = "male" # 鍵不存在,It is to add key-value pairs
stu["age"] = 24 # 鍵存在,Then modify the key-value pair
print(stu)
# 刪除鍵值對 del命令
del stu["gender"]
print(stu)

8.字典的內置方法

# 字典的內置方法:Data management for dictionary objects
stu = {
"name": "yuan", "age": 22, "gender": "female"}
# 一 查看鍵值對
# print(stu.get("name"))
# print(stu.get("age"))
# print(stu.get("gender", "male"))
# print(stu.keys()) # ['name', 'age']
# print(stu.values()) # ['yuan', 22]
# print(stu.items()) # [('name', 'yuan'), ('age', 22)]
# 二 添加或修改鍵值對:update
# stu.update({"age":32,"gender":"male"})
# ret = stu.setdefault("gender", "male") # 獲取name鍵的值
# print(ret)
# print(stu)
# 三 刪除鍵值對:pop
# ret = stu.pop("age")
# stu.popitem()
# print("age",ret)
# print("stu",stu)

9. 字典的for循環

stu = {
"name": "yuan", "age": 22, "gender": "female"}
# print(stu.get("name"))
# k = "age"
# print(stu.get(k))
# 方式1
# for i in stu:
# print(i, stu.get(i)) # 遍歷字典的鍵
# 方式2
# x = [1, 2, 3]
# print(x, type(x)) # tuple
# a, *b = [1, 2, 3]
# print(a, b)
for k,v in stu.items(): # [("name","yuan")],("age",22),("gender","male)]
print(k,v)

10.元組類型

# Tuples are called read-only lists
l = [1, 2, 3]
l[0] = 100
t = (1, 2, 3)
print(t, type(t)) # tuple
print(t[1])
print(t[1:])
print(1 in t)
t.count(1)
t.index(1)
for i in t:
print(i)

11.字典的使用

# 練習1
stu = {
"name": "yuan", "score": [100, 90, 80]}
# Get foreign language grades
l = stu.get("score") # [100, 90, 80]
print(l[-1])
print(stu.get("score")[-1])
# 練習2
stu = {
"name": "yuan", "score": {
"chinese": 100, "math": 90, "english": 80}}
print(len(stu))
print(stu.get("score").get("english"))
# 練習3
data = [
{
"sid":1001,"name": "rain", "age": 22},
{
"sid":1003,"name": "eric", "age": 32},
{
"sid":1002,"name": "alvin", "age": 24},
]
for stu_dict in data:
name = stu_dict.get("name")
age = stu_dict.get("age")
print("姓名:%s,年齡:%d" % (name, age))
data2 = {

1001: {
"name": "rain", "age": 22},
1002: {
"name": "eric", "age": 32},
1003: {
"name": "alvin", "age": 24},
}
print(data2.get(1001).get("name"))
for stu_id,stu_info in data2.items():
name = stu_info.get("name")
age = stu_info.get("age")
print("學號:%s,姓名:%s,年齡:%d" % (stu_id,name, age))

12. Dictionary of interview questions

# 案例1
# l1 = [1, 2, 3]
# l2 = [4, 5, l1]
# print(l2) # [4, 5, [1, 2, 3]]
# l1[0] = 100
# print(l2)
# 案例2
stu01 = {
"name": "rain"}
stus_dict = {
1001: stu01}
print(stus_dict)
stu01["name"] = "alvin"
print(stus_dict)
print(id(stus_dict[1001]))
stus_dict[1001] = {
"name": "eric"}
print(id(stus_dict[1001]))
print(id(stu01))

13. 作業

# Determine what data type and format the data is stored in
students_dict = {

1001: {

"name": "yuan",
"scores": {

"chinese": 100,
"math": 89,
"english": 100,
}
},
1002: {

"name": "rain",
"scores": {

"chinese": 100,
"math": 100,
"english": 100,
}
},
}
while 1:
print(''' 1. 查看所有學生成績 2. Add a student grade 3. 修改一個學生成績 4. Delete a student grade 5. 退出程序 ''')
choice = input("請輸入您的選擇:")
if choice == "1":
# 查看所有學生信息
print("*" * 60)
for sid, stu_dic in students_dict.items():
# print(sid,stu_dic)
name = stu_dic.get("name")
chinese = stu_dic.get("scores").get("chinese")
math = stu_dic.get("scores").get("math")
english = stu_dic.get("scores").get("english")
print("學號:%4s 姓名:%4s 語文成績:%4s 數學成績%4s 英文成績:%4s" % (sid, name, chinese, math, english))
print("*" * 60)
elif choice == "2":
while 1:
sid = input("請輸入學生學號>>>")
# Determine whether the student number exists
if int(sid) in students_dict: # 該學號已經存在!
print("該學號已經存在!")
else: # # 該學號不存在!
break
name = input("請輸入學生姓名>>>")
chinese_score = input("請輸入學生語文成績>>>")
math_score = input("請輸入學生數學成績>>>")
english_score = input("請輸入學生英語成績>>>")
# Build a student dictionary
scores_dict = {

"chinese": chinese_score,
"math": math_score,
"english": english_score,
}
stu_dic = {

"name": name,
"scores": scores_dict
}
print("stu_dic", stu_dic)
students_dict[int(sid)] = stu_dic
elif choice == "3":
while 1:
sid = input("請輸入學生學號>>>")
# Determine whether the student number exists
if int(sid) in students_dict: # 該學號已經存在!
break
else: # # 該學號不存在!
print("The modified student ID does not exist!")
chinese_score = input("請輸入學生語文成績>>>")
math_score = input("請輸入學生數學成績>>>")
english_score = input("請輸入學生英語成績>>>")
# 修改學生成績
scores_dict = {

"chinese": chinese_score,
"math": math_score,
"english": english_score,
}
students_dict.get(int(sid)).update({
"scores": scores_dict})
print("修改成功")
elif choice == "4":
while 1:
sid = input("請輸入學生學號>>>")
# Determine whether the student number exists
if int(sid) in students_dict: # 該學號已經存在!
break
else: # # 該學號不存在!
print("The modified student ID does not exist!")
students_dict.pop(int(sid))
print("刪除成功")
elif choice == "5":
# 退出程序
break
else:
print("輸入有誤!")

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved