我以這兩個元組串列為例:
l1 = [(3364, 183, 8619),
(8077, 124, 6142),
(3776, 166, 7385),
(8874, 11, 9453),
(12917, 225, 12433),
(2567, 54, 8188),
(11919, 82, 2062),
(10698, 108, 12151)]
第二個清單:
l2 = [(3364, 183, 20),
(8077, 124, 21),
(3776, 166, 22),
(8874, 11, 23),
(12917, 225, 24),
(2567, 54, 25),
(11919, 82, 26),
(10698, 108, 27)]
1 -我通過執行以下條件從兩個串列中創建一個帶有“串列理解”的新串列:對于串列中的每個元組,元組的第一個元素等于第二個串列中每個元組的第一個元素我可以插入值 p [0],p [1](第一個串列)和第二個串列的 n [0],實際上:
new_list = list(set([(p[0],p[1],n[2]) for n in l2 for p in l1 if p[0] == n[0]]))
2 -然后我將三元組分解為一個串列:
new_list = [n for n2 in new_list for n in n2]
3 -我將元組分解為一個串列,因為稍后我將通過從該串列中隨機選擇值來創建一個陣列,即:
new_elements = np.random.choice(new_list, size =512)
問題是什么 ?
當串列 l1 和 l2 中有大量元組時,步驟1和2運行時間過長。你能告訴我我錯在哪里,或者是否有更有效的方法可以更好地執行?
我希望我已經最好地解釋了我的問題。
例子:
l1 = [(10,11,2), l2 = [(10,11,3),
(9,10,4)] (9,10,5)]
后 :
new_list = list(set([(p[0],p[1],n[2]) for n in l2 for p in l1 if p[0] == n[0]]))
輸出:
new_list = [(10,11,3),
(9,10,5)]
uj5u.com熱心網友回復:
我們可以使用字典來索引您的p[0]和n[0]
d1 = {p[0]: p[1] for p in l1}
d2 = {n[0]: n[2] for n in l2}
在這里我放棄了p[2],n[1]因為它們在未來的步驟中無關緊要。
然后我們根據您的需要找到兩個鍵的交集
intersection = d1.keys() & d2.keys()
最后new_list根據您的第 3 步需要構建
new_list = list(intersection) list(map(d1.get, intersection)) list(map(d2.get, intersection))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/420094.html
標籤:
上一篇:將卡方應用于包含分類變數的資料集
下一篇:使用numpy向量化矩陣運算
