你好,
我有許多長度不同的列表,我想將列表中的所有項目合併到一個列表中。
例如:
list1 = {"a", "b", "c"};
list2 = {"d", "e"};<BR />list3 = {"f", "g", "h", "i"};<BR />.... the number of lists ranges from 7 to 10.
想要創造
list = {"a", "b", "c", "d", "e"};
我一直在創建最終清單
Insert Into(list1, list2);
Insert Into(list1, list3);
.... and so on. <BR />(I don't mind the list items are added to list1)
有沒有更有效的方法來做到這一點? Insert Into() 似乎不接受超過 1 個附加參數。
謝謝。
如果您樂意更新 list1,這就是您能做的最好的事情。
如果您想要一個新列表,而保持舊列表不變,那麼最好的選擇是
lnew = l1 || l2 || l3;
// vs
lnew = insert( l1, l2 ); lnew = insert( lnew, l3 );
取決於列表的長度,但 ||最終在下圖中領先。
三個都在相同速度的 2 倍以內。 我喜歡 insertInto() 因為它避免了複製 list1。 我喜歡||連接運算符,因為很清楚它在做什麼。
InsertInto wins if you don't mind that it does what its name says.如果您不介意 InsertInto 的功能如其名稱所示,那麼 InsertInto 會獲勝。