python學習的第八天
- 前言
- 字典
- 用戶輸入
前言
今天是學習python的第8天,上次學到了遍歷字典中的值了,你還記得嘛,不記得了可以去復習一下哦,咱們直接開始
字典
這里分享一個set函式的用法,使得重復的元素只顯示一個
favorite_language = {'jen':'Python',
'sarah':'c',
'edward':'ruby',
'phil':'Python'
}
print("The following languages have been mentioned:")
for language in set(favorite_language.values()):#這里使用了一個set函式來提取favorite中不同的語言,避免重復,這里是利用set創建一個集合(集合的性質)
print(language.title())
結果:
The following languages have been mentioned:
C
Ruby
Python
嵌套
有時候需要將字典儲存在串列中,或者將串列儲存在字典中,這種方式就叫做嵌套,
字典串列
alien_0 = {'color':'green','points':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'red','points':15}
aliens= [alien_0,alien_1,alien_2]#這里不需要加上單引號或者雙引號,因為加上之后會把這些當成字串,輸出的只是字典的名稱
for alien in aliens:
print(alien)
結果:
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}
這里是定義字典,再嵌入串列中,
嵌入任意數量的字典
#創建一個空白串列用于儲存外星人
aliens = []
#創建30個綠色的外星人
for alien_number in range(30):#核心操作,控制了數量
new_alien = {'color':'green','points':5}
aliens.append(new_alien)#每進行了一次,就進行擴充
#顯示前5個外星人,
for alien in aliens[:5]:#這里使用了切片,可以完整的從開始到末尾開始
print(alien)
print("...")
print(f"Total number of aliens:{len(aliens)}")#這里用來Len函式對其進行了計算
結果:
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5}
…
Total number of aliens:30
對串列中的字典進行修改
#創建一個空白串列用于儲存外星人
aliens = []
#創建30個綠色的外星人
for alien_number in range(30):#核心操作,控制了數量
new_alien = {'color':'green','points':5}
aliens.append(new_alien)#每進行了一次,就進行擴充
#修改前三個外星人的資訊
for alien in aliens[:3]:
if alien['color'] =='green':
alien['color'] ='yellow'
alien['points'] = 10 #別忘了這里是串列中嵌套字典 alien是新的變數能夠代替字典 new_alien
for alien in aliens[0:5]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['points'] = 15
#顯示前5個外星人,
for alien in aliens[:5]:#這里使用了切片,可以完整的從開始到末尾開始
print(alien)
print("...")
print(f"Total number of aliens:{len(aliens)}")#這里用來Len函式對其進行了計算
結果:
{‘color’: ‘red’, ‘points’: 15}
{‘color’: ‘red’, ‘points’: 15}
{‘color’: ‘red’, ‘points’: 15}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘yellow’, ‘points’: 10}
…
Total number of aliens:30
使用新字典來代替原來的字典
在字典中儲存串列
就拿pizza做例子吧,pizza有很多口味,而且有許多配方,而配方中又不止一直材料這個時候就需要使用串列來存盤了,
#存盤所點pizza的資訊
pizza = {'crust':'thick',
'toppings':['mushroom','extra cheese']#直接在字典資訊中輸入一個串列即可
}
#概述所點的比薩,
print(f"You ordered a {pizza['crust']}-crust pizza"
f" with the following toppings:")#如果print的陳述句太長可以換行,但是每一行需要的陳述句需要一個雙引號
for topping in pizza['toppings']:
print("\t"+topping)#這里如果不使用“+”號程式會呈現錯誤,運行不出來,
結果:
You ordered a thick-crust pizza with the following toppings:
mushroom
extra cheese
注意代碼中的注釋哦
實戰
favorite_languages = {
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}#上述操作建立一個含串列的字典
for name,languages in favorite_languages.items():#這里是遍歷了一下鍵值對,所以需要使用到items()方法,
print(f"\n{name.title()}'s favorite languages are:")#這里是列印出鍵
for language in languages:#這里是對值進行列印,但是因為是一個串列所以需要來遍歷
print(f"\t{language.title()}")
結果:
Jen’s favorite languages are:
Python
Ruby
Sarah’s favorite languages are:
C
Edward’s favorite languages are:
Ruby
Go
Phil’s favorite languages are:
Python
Haskell
在字典中存盤字典
好比如每個人都有自己的名字,同時他們也有很多自己的賬戶用戶名,這個時候我們需要使用這個了字典中嵌套字典了
users = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},#這里是字典包含字典
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris'
},
}
for username,user_infor in users.items():#這里是遍歷整個字典,username代表的是名字,user_infor代表的是字典
print(f"\nUsername:{username}")#列印名字
full_name = f"{user_infor['first']}{user_infor['last']}"#建立了一個新變數 = 花括號內的變數都是字典中的內容
location = user_infor['location']
print(f"\tFull name:{full_name.title()}")
print(f"\tLocation:{location}")
結果:
Username:aeinstein
Full name:Alberteinstein
Location:princeton
Username:mcurie
Full name:Mariecurie
Location:paris
用戶輸入
函式input的作業原理
函式input()會讓程式暫停運行,等待用戶輸入一些文本,獲取用戶輸入后,python將其賦給一個變數,以方便你的使用
message = input("Tell me something,and I will repeat it back to "
"you:")#這里是相當于c語言中的scanf但是會更加的方便,可以看到提示資訊后再輸入
print(message)
結果:
Tell me something,and I will repeat it back to you:yinyanghaixing#我所輸入的
yinyanghaixing
如果我們所需要的提示太多了,我們可以多使用一個變數來代替
prompt = "If you tell us who you are,we can personalize the massage you see."
prompt +="\n What's your name"
name = input(prompt)
print(name)
結果:
If you tell us who you are,we can personalize the massage you see.
What’s your nameyinyang
yinyang
使用int()來獲得數值輸入
>>> age = input('How old are you?')
How old are you?21
>>> age
'21'#這里是python直接將其定義為了字串型別
>>> age > 18#將其與數值進行計較時,程式會出現錯誤,因為一個時 ‘str’型別一個是‘int’類不能進行比較
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
age > 18
TypeError: '>' not supported between instances of 'str' and 'int'
>>> age = int(age)#使用int函式將age轉換為int型別
>>> age > 18
True#從而可以進行比較
這一次都是大片的代碼,所以要認真的分析看下,如有錯誤歡迎評論區指出,謝謝,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/281265.html
標籤:python
上一篇:Python撰寫動量交易策略
下一篇:Python入門到實戰(五)自動化辦公、pandas操作Excel、資料可視化、繪制柱狀圖、操作Word、資料報表生成、pip install國內鏡像下載
