我的解決方案是基於您試圖通過詞典列表進行搜索的假設,因此我已經更正了列表。如果列表中的字典不包含您正在搜索的密鑰,則還會出現錯誤。爲此,我爲該函數添加了簡單的錯誤處理。
我是一個Python新手,所以可能存在比我更優雅的解決方案,但它可能已經足夠滿足您的需求。它的工作原理是這樣的:如果找到值爲'111'的關鍵'活動'的發生,則利用'值121'搜索關鍵'活動'的其餘部分。夠簡單。
但是,如果你只考慮條件滿足,如果活動121活動111發生後的第二天詞典中找到,你可以簡單地改變線14本:
if i[key] == valueTwo and foundOne and (dictCount - 1) == countHelp:
而且,我不確定你是否試圖在活動111之後找到第一個找到活動121的詞典,或者如果你想寫出整個詞典列表。變量'myDictionaries'是整個列表,變量'i'只是第一個字典,其中活動121在活動111之後被發現。
您將從第16行寫入,在我的解決方案中,歸檔。所以只需將其更改爲您的文件編寫解決方案。
# -*- coding: utf-8 -*-
from __future__ import print_function # You can remove this line if you're using Python 3.
def searchDictionaries(key, valueOne, valueTwo, myDictionaries): # Define the function with four arguments
dictCount = 0 # Initialize the count of dictionaries in the list
foundOne = False # Initialize the state for meeting the first condition
countHelp = 0 # This will help us determine if the second condition is met in the dictionary right after the first condition was met
for i in myDictionaries: # Start looping through the list of dictionaries
dictCount = dictCount + 1 # Increase count at every iteration
try:
if i[key] == valueOne: # Check if the first condition is met (if the value of activity is 111)
foundOne = True # Change the state of meeting the first condition to True
countHelp = dictCount # Keep this in case you want to modify the next line to only search in the next dictionary
if i[key] == valueTwo and foundOne: # Check if the second condition (activity value of 121) is present in any subsequent dictionary
# If you made it here, both conditions were met and you can write to file
print(myDictionaries) # Write the whole list of dictionaries to file. Use print(i) if you want to just print the first dictionary where you found 121 after 111 was found.
break # Stop searching
except Exception as e: # Error handling
print('Warning: %s - There is no key %s in dictionary %s.' % (e, e, dictCount))
return
# Your example list of dictionaries
myListOfDicts = [
{'activity': '111', 'interface': 'eds', 'clientIp': '12.207.212.130', 'logTime': 1469811993000},
{'session': -2147479722, 'dbCount': 33, 'totalHits': 24, 'query': 'TI', 'the': 'plague', 'searchedFrom': 'Unknown', 'searchType': 'And', 'logTime': 1469811994000},
{'activity': '121', 'customerId': 's8905647', 'groupId': 'main', 'profileId': 'eds'}
]
# Now you can call the function searchDictionaries with your desired values > key, first value, second value, name of your list of dictionaries
searchDictionaries('activity', '111', '121', myListOfDicts)
我希望別人能幫助您與任何後續問題,因爲我沒有足夠的積分,使用註釋功能。
你的意思是這個列表是一個字符串看起來像字典的單元素列表?或者它應該是一個字典清單? – SO44
您應該在字符串上使用'json.loads()'。這將返回一個更簡單,更高效的字典。 – IanAuld