簡體   English   中英

列表字典

[英]Dictionary of Lists

我正在嘗試構建一個列表字典,但我正在讀取一個字符串,需要使列表命名為字符串,並將它們作為鍵添加到字典中。

IE讀入“你好”

使用讀入的內容創建列表

List<string> (insert read string here ) = new List<string>();

然后添加該列表名稱作為字典的鍵。

Dictionary.Add(readstring, thatlist);

我能找到的只是硬代碼實現。

Turing.Add("S", S);

我的目標是:創建一個通用圖靈機,所以我讀入了一個文本文件的輸入,這是下一步看起來像這樣,(q0 a) - > q1 X R.

然后在虛擬磁帶“tape = XXYYZZBB”上使用我讀入的所有步驟以最終狀態結束

我有為此編寫的偽代碼,但我不能讓字典工作。

編輯:添加更多信息以減少混淆。 我給出了文本文件前兩行的開始和結束狀態。 然后我給出了過渡。

q0 //開始狀態q5 //結束狀態q0 a q1 XR //轉換

我剝離了前兩行輸入,給我0和5然后創建了一個for循環來創建每個狀態的列表。

for (int i = 0; i <= endState; i++)
{
List<string> i = new List<string>();
}

然后我想將每個列表名稱添加為我正在創建的列表字典的鍵。

Dictionary.Add(listname, thatlist);

我需要幫助實現上面的代碼作為給出錯誤。

您是否將列表創建為無關緊要

List<string> insertReadStringHere = new List<string>();

要么

List<string> foo = new List<string>();

甚至

List<string> shellBeComingRoundTheMountain = new List<string>();

一旦你做完了,重要的是什么

MyDictionary.Add(theInputString, shellBeComingRoundTheMountain);

然后,您可以通過訪問該特定列表

MyDictionary[theInputString]

其中,初始列表是“調用” insertReadStringHerefooshellBeComingRoundTheMountain

您甚至不需要將列表保存在這樣的命名變量中。 例如,

Console.WriteLine("Input a string to create a list:");
var createListName = Console.ReadLine();
// As long as they haven't used the string before...
MyDictionary.Add(createListName, new List<string>());

Console.WriteLine("Input a string to retrieve a list:");
var retrieveListName = Console.ReadLine();
// As long as they input the same string...
List<string> retrievedList = MyDictionary[retrieveListName];

編輯:如果您想要一定數量的列表,請使用從int到string的字典,而不是字符串到字符串:

int maxNumberOfLists = 5; // or whatever you read from your text file.
Dictionary<int, List<string>> myLists =
            new Dictionary<int, List<string>> (maxNumberOfLists);
for (int i = 1; i <= maxNumberOfLists; i++)
    myLists[i] = new List<string>();

然后,您可以訪問您的列表,例如

var firstList = myLists[1];

通常我會推薦一個數組,但這會給你1到5而不是0到4的列表,看起來這就是你想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM