[英]Efficient way to look in list of lists?
我不斷創建一個隨機生成的列表, New_X
,大小為10,基於500列。
每次我創建一個新列表時,它必須是唯一的,並且我的函數NewList
只有在尚未創建並返回New_X
NewList
后才返回List_Of_Xs
def NewList(Old_List):
end = True
while end == True:
""" Here is code that generates my new sorted list, it is a combination of elements
from Old_List and the other remaining columns,
but the details aren't necessary for this question. """
end = (List_Of_Xs == np.array([New_X])).all(axis=1).any()
List_Of_Xs.append(New_X)
return New_X
我的問題是,行end = (List_Of_Xs == np.array([New_X])).all(axis=1).any()
是一種查看List_Of_Xs
的有效方法嗎?
我的List_Of_Xs
可以長到超過100,000個列表,所以我不確定這是否效率低。
任何幫助,將不勝感激!
所以讓我直截了當,因為代碼看起來並不完整:1。你有一個舊的列表,每次迭代都在不斷增長2.你計算一個列表3.你將它與舊列表中的每個列表進行比較看看你是否應該打破循環?
一種選擇是將列表存儲在集合中而不是列表列表中。 將元素與列表的所有元素進行比較將是每次迭代的O(n)操作。 使用一個集合它應該是O(1)avg ...雖然你可能每次迭代都得到O(n)直到最后一次。
其他想法是計算每個元素的md5並進行比較,這樣你就不會比較完整列表。
正如我在評論中觀察到的那樣,數組比較可能非常慢,特別是當列表變大時。 它必須每次都創建數組,這會消耗時間。
這是一個集合實現
創建10個元素列表的函數:
def foo(N=10):
return np.random.randint(0,10,N).tolist()
用於生成列表和打印唯一列表的功能
def foo1(m=10):
Set_of_Xs = set()
while len(Set_of_Xs)<m:
NewX = foo(10)
tx = tuple(NewX)
if not tx in Set_of_Xs:
print(NewX)
Set_of_Xs.add(tx)
return Set_of_Xs
樣品運行。 如上所述,它沒有顯示是否有重復。
In [214]: foo1(5)
[9, 4, 3, 0, 9, 4, 9, 5, 6, 3]
[1, 8, 0, 3, 0, 0, 4, 0, 0, 5]
[6, 7, 2, 0, 6, 9, 0, 7, 0, 8]
[9, 5, 6, 3, 3, 5, 6, 9, 6, 9]
[9, 2, 6, 0, 2, 7, 2, 0, 0, 4]
Out[214]:
{(1, 8, 0, 3, 0, 0, 4, 0, 0, 5),
(6, 7, 2, 0, 6, 9, 0, 7, 0, 8),
(9, 2, 6, 0, 2, 7, 2, 0, 0, 4),
(9, 4, 3, 0, 9, 4, 9, 5, 6, 3),
(9, 5, 6, 3, 3, 5, 6, 9, 6, 9)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.