簡體   English   中英

在 Json 數組(數組字典)中搜索元素的有效方法

[英]An efficient way to search elements in a Json array (dictionary of arrays)

我正在編寫一個腳本,將兩個 Json 文件讀入字典

字典或多或少是相似的,就像這樣

{  "elements":[
    {
     "element_id":0,
     "thedata":{
                "this": 5
               }
     },
     {
     "element_id":4,
     "thedata":{
                "this": 5
               }
     }
    {
      ...
    }
]}

到目前為止,我假設element_id從 0 開始增加 1 到 1 然后要求改變了,這次他們從 0 開始增加 4 到 4 或類似這樣

不管怎樣,到目前為止,我認為兩個詞典都有相同數量的元素和相同的遞增距離,所以當我在腳本中得到這些元素時,我寫了類似

def process_elements(number):
    el1_id=thedictionary['elements'][number]['element_id']
    el2_id=thedictionary2['elements'][number]['element_id']
    assert(el1_id==el2_id)
    #here work with the data 

但是要求又變了

現在一個字典的元素數量不一定與另一個相同也不能保證其中一個總是從 0 開始

所以現在我必須在兩個字典中找到具有相同元素 id 的元素

所以我的問題是,在上面的字典(來自 json)中,有沒有一種快速的方法可以找到具有特定element_id的元素並獲取該元素?

就像是

def process_elements(number):
    el1_id=thedictionary['elements'][number]['element_id']

    n=find_i(thedictionary2,el1_id) #finds the index with the element that has id the same as el1_id
    el2_id=thedictionary2['elements'][n]['element_id']
    assert(el1_id==el2_id)  #Of course they are the same since we used find_i
    #here work with the data 

它必須很快,因為我將它用於 animation

我不知道為什么刪除了這個問題的優秀答案(而且似乎也是用戶)。 所以我會在這里發布答案,以便其他人可以使用它。 (感謝 Khaoz-07)


如果您需要在字典中查找具有特定 element_id 的多個元素,並且希望盡可能高效地執行此操作,則可以使用字典來存儲具有給定 element_id 的元素。 然后,當您需要查找具有特定 element_id 的元素時,您可以使用 element_id 作為鍵在字典中查找它,而不必遍歷字典中的元素。

這是您如何執行此操作的示例:

# Create a dictionary to store the elements with a given element_id
elements_by_id = {}

# Iterate over the elements in the dictionary
for element in thedictionary['elements']:
    # Get the element_id for the current element
    element_id = element['element_id']

    # Check if the element_id is already a key in the elements_by_id dictionary
    if element_id not in elements_by_id:
        # If the element_id is not already a key in the dictionary, create a new key-value pair in the dictionary,
        # with the element_id as the key and an empty list as the value
        elements_by_id[element_id] = []

    # Add the current element to the list of elements with the given element_id
    elements_by_id[element_id].append(element)

# Now, when you need to find the elements with a particular element_id, you can just look it up in the dictionary
# using the element_id as the key
found_elements = elements_by_id[4]

# Print the found elements to the console
print(found_elements)

這種方法比遍歷字典中的元素並檢查每個元素的 element_id 值更有效,因為它只需要一次遍歷字典中的元素來創建 elements_by_id 字典,然后您可以查找具有特定 element_id 的元素在恆定的時間。

如果你想讓代碼更快,你可以使用 dict.setdefault() 方法來創建 elements_by_id 字典,一次遍歷字典中的元素。 如果要查找的鍵在字典中不存在,此方法允許您指定要使用的默認值,因此您不必在將鍵添加到字典之前檢查該鍵是否存在。

以下是如何使用 dict.setdefault() 方法創建 elements_by_id 字典的示例:

# Create a dictionary to store the elements with a given element_id
elements_by_id = {}

# Iterate over the elements in the dictionary
for element in thedictionary['elements']:
    # Get the element_id for the current element
    element_id = element['element_id']

    # Use the setdefault() method to create a new key-value pair in the dictionary,
    # with the element_id as the key and an empty list as the value, if the element_id is not already a key in the dictionary
    elements_by_id.setdefault(element_id, [])

    # Add the current element to the list of elements with the given element_id
    elements_by_id[element_id].append(element)

# Now, when you need to find the elements with a particular element_id, you can just look it up in the dictionary
# using the element_id as the key
found_elements = elements_by_id[4]

# Print the found elements to the console
print(found_elements)

這種方法比前面的方法更快,因為它只需要一次遍歷字典中的元素,並且不需要在添加之前檢查 element_id 是否已經是字典中的鍵。

或者,您可以使用 dict.get() 方法獲取具有給定 element_id 的元素列表,並指定一個默認值以在 element_id 作為鍵不存在於字典中時返回。

使用 dict.get() 方法獲取具有給定 element_id 的元素列表的一個優點是,如果 element_id 作為鍵不存在於字典中,它允許您指定要返回的默認值。

這意味着在嘗試訪問具有該 id 的元素之前,您不必使用 in 關鍵字來檢查字典中是否存在 element_id 作為鍵,這可以使代碼更加簡潔和可讀。 不必編寫 if 語句來檢查 element_id 是否作為字典中的鍵存在,您只需使用 dict.get() 方法獲取具有該 id 的元素列表,並指定一個默認值以返回 if element_id 不存在。 這可以使代碼更容易編寫和維護,也可以更容易理解代碼的作用。

使用 get() 方法:

# Create a dictionary to store the elements with a given element_id
elements_by_id = {}

# Iterate over the elements in the dictionary
for element in thedictionary['elements']:
    # Get the element_id for the current element
    element_id = element['element_id']

    # Check if the element_id is already a key in the elements_by_id dictionary
    if element_id not in elements_by_id:
        # If the element_id is not already a key in the dictionary, create a new key-value pair in the dictionary,
        # with the element_id as the key and an empty list as the value
        elements_by_id[element_id] = []

    # Add the current element to the list of elements with the given element_id
    elements_by_id[element_id].append(element)

# Now, when you need to find the elements with a particular element_id, you can use the dict.get() method
# to get the list of elements with the given element_id, and specify a default value to return if the element_id
# doesn't exist as a key in the dictionary
found_elements = elements_by_id.get(34554, [])

# Print the found elements to the console
print(found_elements)

暫無
暫無

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

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