unity3d 詞典訪問
Python字典指南 (Python Dictionary Guide)
The dictionary is one of the data structures that are ready to use when programming in Python.
字典是使用Python進行編程時可以使用的數據結構之一。
在我們開始之前,什么是字典? (Before We Start, What is a Dictionary?)
Dictionary is an unordered and unordered Python collection that maps unique keys to some values. In Python, dictionaries are written by using curly brackets {}
. The key is separated from the key by a colon :
and every key-value pair is separated by a comma ,
. Here’s how dictionaries are declared in Python.
字典是一個無序且無序的Python集合,它將唯一鍵映射到某些值。 在Python中,字典使用大括號{}
編寫。 的密鑰是從一個冒號鍵分離:
與每一個鍵-值對由逗號分隔,
。 這是在Python中聲明字典的方式。
#A dictionary containing basketball players with their heights in m
playersHeight = {"Lebron James": 2.06,
"Kevin Durant": 2.08,
"Luka Doncic": 2.01,
"James Harden": 1.96}
We have created the dictionary, however, what’s good about it if we cannot retrieve the data again right? This is where a lot of people do it wrong. I should admit, I was among them not long ago. After I realize the advantage, I never turn back even once. That’s why I am motivated to share it with you guys.
我們已經創建了字典,但是,如果我們不能再次正確檢索數據,那有什么用呢? 這是很多人做錯事的地方。 我應該承認,不久前我就是其中之一。 意識到優勢之后,我再也不會回頭一次。 這就是為什么我有動力與大家分享。
錯誤的方法 (The Wrong Way)
The well-known, or I should say the traditional way to access a value in a dictionary is by referring to its key name, inside a square bracket.
眾所周知,或者我應該說在字典中訪問值的傳統方法是在方括號內引用其鍵名。
print(playersHeight["Lebron James"]) #print 2.06
print(playersHeight["Kevin Durant"]) #print 2.08
print(playersHeight["Luka Doncic"]) #print 2.01
print(playersHeight["James Harden"]) #print 1.96
Everything seems OK, right? Not so fast! What do you think will happen if you type a basketball player’s name that is not in the dictionary? Look closely
一切似乎還好吧? 沒那么快! 如果您鍵入詞典中沒有的籃球運動員的名字,您會怎么辦? 仔細看
playersHeight["Kyrie Irving"] #KeyError 'Kyrie Irving'
Notice that when you want to access the value of the key that doesn’t exist in the dictionary will result in a KeyError. This could quickly escalate into a major problem, especially when you are building a huge project. Fret not! There are certainly one or two ways to go around this.
請注意,當您要訪問字典中不存在的鍵的值時,將導致KeyError。 這可能很快會升級為一個主要問題,尤其是在構建大型項目時。 不用擔心! 解決這個問題肯定有一兩種方法。
Using If
使用If
if "Kyrie Irving" is in playersHeight:
print(playersHeight["Kyrie Irving"])
Using Try-Except
使用Try-Except
try:
print("Kyrie Irving")
except KeyError as message:
print(message) #'Kyrie Irving'
Both snippets will run with no problem. For now, it seems okay, we can tolerate writing more lines to deal with the possibility of KeyError. Nevertheless, it will become annoying when the code you are writing is wrong.
兩個片段都可以正常運行。 就目前而言,似乎還可以,我們可以忍受寫更多的行來解決KeyError的可能性。 但是,當您編寫的代碼錯誤時,它將變得很煩人。
Luckily, there are better ways to do it. Not one, but two better ways! Buckle up your seat and get ready!
幸運的是,有更好的方法可以做到這一點。 不是一種,而是兩種更好的方法! 系好安全帶,準備好!
正確的方式 (The Right Way)
Using get() Method
使用get()方法
Using the get method is one of the best choices you can make when dealing with a dictionary. This method has 2 parameters, the first 1 is required while the second one is optional. However, to use the full potential of the get()
method, I suggest you fill both parameters.
使用get方法是處理字典時最好的選擇之一。 此方法有2個參數,第一個參數是必需的,第二個參數是可選的。 但是,要充分利用get()
方法的潛力,建議您同時填寫兩個參數。
- First: the name of the key which value you want to retrieve 第一:密鑰名稱要檢索的值
- Second: the value used if the key we are searching does not exist in the 第二:如果要搜索的鍵不存在,則使用該值
#A dictionary containing basketball players with their heights in m
playersHeight = {"Lebron James": 2.06,
"Kevin Durant": 2.08,
"Luka Doncic": 2.01,
"James Harden": 1.96}#If the key exists
print(playersHeight.get("Lebron James", 0)) #print 2.06
print(playersHeight.get("Kevin Durant", 0)) #print 2.08#If the key does not exist
print(playersHeight.get("Kyrie Irving", 0)) #print 0
print(playersHeight.get("Trae Young", 0)) #print 0
When the key exists, get()
method works exactly the same to referencing the name of the key in a square bracket. But, when the key does not exist, using get()
method will print the default value we enter as the second argument.
當鍵存在時, get()
方法的工作原理與在方括號中引用鍵的名稱完全相同。 但是,當鍵不存在時,使用get()
方法將打印我們輸入的默認值作為第二個參數。
If you don’t specify the second value, a None
value will be returned.
如果您未指定第二個值,則將返回None
值。
You should also note that using the get()
method will not modify the original dictionary. We will discuss it further later in this article.
您還應該注意,使用get()
方法不會修改原始字典。 我們將在本文后面進一步討論。
Using setdefault() method
使用setdefault()方法
What? There is another way? Yes of course!
什么? 還有另一種方法嗎? 當然是!
You can use setdefault()
method when you not only want to skip the try-except step but also overwrite the original dictionary.
當您不僅要跳過try-except步驟而且要覆蓋原始字典時,可以使用setdefault()
方法。
#A dictionary containing basketball players with their heights in m
playersHeight = {"Lebron James": 2.06,
"Kevin Durant": 2.08,
"Luka Doncic": 2.01,
"James Harden": 1.96}#If the key exists
print(playersHeight.setdefault("Lebron James", 0)) #print 2.06
print(playersHeight.setdefault("Kevin Durant", 0)) #print 2.08#If the key does not exist
print(playersHeight.setdefault("Kyrie Irving", 0)) #print 0
print(playersHeight.setdefault("Trae Young", 0)) #print 0
What I mean by overwriting is this, when you see the original dictionary again, you will see this.
我的意思是重寫,當您再次看到原始詞典時,您將看到此。
print(playersHeight)
"""
print
{"Lebron James": 2.06,
"Kevin Durant": 2.08,
"Luka Doncic": 2.01,
"James Harden": 1.96,
"Kyrie Irving": 0,
"Trae Young": 0}
Other than this feature, the setdefault()
method is exactly similar to the get()
method.
除了此功能外, setdefault()
方法與get()
方法完全相似。
最后的想法 (Final Thoughts)
Both get()
and setdefault()
are advanced techniques that you all must familiarize with. Implementing it is not hard and straightforward. The only barrier for you now is to break those old habits.
get()
和setdefault()
都是您都必須熟悉的高級技術。 實施它并不困難和直接。 現在,您的唯一障礙是打破這些舊習慣。
However, I believe that as you use it, you will experience the difference immediately. After a while, you will no longer hesitate to change and start using get()
and setdefault()
methods.
但是,我相信,當您使用它時,您會立即體驗到不同之處。 一段時間后,您將不再需要更改并開始使用get()
和setdefault()
方法。
Remember, when you don’t want to overwrite the original dictionary, go with get()
method.
請記住,當您不想覆蓋原始字典時,請使用get()
方法。
When you want to make changes to the original dictionary, setdefault()
will be the better choice for you.
當您想更改原始字典時, setdefault()
將是您的更好選擇。
Regards,
問候,
Radian Krisno
拉迪安·克里斯諾(Radian Krisno)
翻譯自: https://towardsdatascience.com/the-right-way-to-access-a-dictionary-7a19b064e62b
unity3d 詞典訪問
本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。 如若轉載,請注明出處:http://www.pswp.cn/news/387989.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/387989.shtml 英文地址,請注明出處:http://en.pswp.cn/news/387989.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!