[英]In python I do “dictionary = {”key“: [value, value], (etc)}” How do I do this in Visual Basic?
我正在VB中為我的計算機科學課做一個小型冒險游戲,並且要對角色進行盤點,我需要知道如何制作字典(這樣我才能得到商品的名稱)和清單作為值項目(列表類似於obj = [Quantity,Damage_Dealt(或Health_Received)])。 我做了一些研究,我試圖做
Dim knife As New List(Of Integer)
knife.add(1)#the first one is how many knives and the second is the dmg
knife.add(1)
Dim inv As New Dictionary(Of String, List(Of Integer))
inv.add("knife", knife)
但是有些東西丟失了,或者希望有一種更簡單的方法可以做到。 即使可以創建2或3維數組(例如inv = [[knife, 1, 1], [bread, 2, 0]]
)
我將很欣賞更改python的最直接方法
dictionary = {"key": [value, value], (etc)}
進入VB提前謝謝
我忘了提到所有在類中的子類中。
您完全可以制作一個新列表(字典(字符串,列表(整數)))並填充它。
您似乎已經知道代碼了。 祝您實施愉快!
這是一個如何完成您要尋找的東西的基本示例。
Public Sub TestData()
//Create List and populate it
Dim list As New List(Of KeyValuePair(Of String, List(Of Integer)))
Dim integerList As List(Of Integer) = New List(Of Integer)
integerList.Add(1)
integerList.Add(2)
list.Add(New KeyValuePair(Of String, List(Of Integer))("Test", integerList))
//Iterate through the list to get data
For Each pair As KeyValuePair(Of String, List(Of Integer)) In list
Dim key As String = pair.Key
Dim newIntegerList As New List(Of Integer)
For Each value As Integer In pair.Value
newIntegerList.Add(value)
Next
Next
End Sub
編輯:不得不將注釋更改為C#注釋,因為它不喜歡VB注釋。 但是顯然您會擺脫這些。
有多種方法可以通過創建列表字典或數組字典來實現。 但是,如果必須依靠索引來查找正確的屬性,則代碼將變得混亂。
更好的選擇是使用元組 ; 但是,這些被更多地認為是用於臨時存儲,用於中間結果以及用於返回多個值的函數。
項目是游戲的重要方面。 創建一個Item類! 這將使您更輕松地處理物品
Public Class Item
Property Quantity As Integer
Property Damage As Integer
Property Health As Integer
End Class
您可以使用
Dim Items As New Dictionary(Of String, Item) From {
{"knife", New Item With {.Quantity = 1, .Damage = 0, .Health = 100}},
{"arrow", New Item With {.Quantity = 5, .Damage = 0, .Health = 100}}
}
現在,您可以輕松檢索屬性
Dim knifeDamage = Items("knife").Damage
類還具有其他優點:您可以向其添加Subs和Function,可以派生具有僅適用於它們的屬性的更多特定項目類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.