2017-07-17 122 views
1

所以我的問題是,我想追加一個名稱的東西到一個數組,並計數。追加和搜索多維數組

test_array = [] 
test_array.append(['apples', 2]) 
test_array.append(['oranges', 5]) 
test_array.append(['bananas', 1]) 

print(*test_array) 

['apples', 2] 
['oranges', 5] 
['bananas', 1] 

現在我想通過我指望的東西的名字來搜索我的二維數組,並添加1到第二列

test_array['oranges'][1] = test_array['oranges'][1]+1 

我會加入之前測試該項目的存在1到第二列

if test_array['string'] != None: 
    test_array.append['string', ] 

我不知道這是可能的,或者如果我將只需要追加到列表之前搜索的數組中項目的整個第一列。我將這樣做37,731,481項,所以我需要一種方法來搜索字符串,希望在運行時不會是二次的,所以我可能只是按字符串排序我的列表並進行二分搜索。

+0

我想你需要在追加之前搜索整個數組的第一列。看起來好像字典可能會是一個更好的數據結構:https://docs.python.org/3/tutorial/datastructures.html#dictionaries –

回答

1

我建議你使用映射而不是嵌套列表,最好是collections.Counter對象。這些項目將是鍵和他們的計數將是值。然後搜索一個密鑰可以在一段時間內完成 - O(1)。

from collections import Counter 

dct = Counter() 
dct['apples'] = 2 
dct['oranges'] = 5 
dct['bananas'] = 1 
print dct 
# Counter({'oranges': 5, 'apples': 2, 'bananas': 1}) 

而且你不會需要測試關鍵存在添加/更新值:

# updating a key (which is not in the counter) 
dct['mango'] += 3 
print dct 
# Counter({'oranges': 5, 'apples': 2, 'mango': 3, 'bananas': 1}) 

這是因爲不像香草類型的字典collections.Counter對象總是丟失的鑰匙返回零,而不是養KeyError

如果您需要管理負數,Counter對象不是最佳選擇。你可以使用一個collections.defaultdict對象,而不是使default_factoryint功能:

from collections import defaultdict: 

dct = defaultdict(int) 
... 

的工作方式爲Counter除了負計數現在正確處理相同。