2016-08-05 109 views
-2

我有這個名單如何找到一個列表元素

['{"activities":[{"activity":"111","interface":"eds","clientIp":"12.207.212.130","logTime":1469811993000},{"activity":"121","dbCount":33,"totalHits":24,"query":"TI', 'the', 'plague","searchedFrom":"Unknown","searchType":"And","logTime":1469811994000}],"session":-2147479722,"customerId":"s8905647","groupId":"main","profileId":"eds"}'] 

,我想這在一個文件中寫入這整個名單隻有"activity":"121"僅存的"activity":"111"發生後,這個名單。就像在這個例子中,第一個"activity":"111"存在,後來"activity":"121"也存在,我希望這個列表寫在文件和任何列表中,其中"activity":"121"不在"activity":"111"之後的任何地方,我不想寫。

我該怎麼做?請幫忙。

+1

你的意思是這個列表是一個字符串看起來像字典的單元素列表?或者它應該是一個字典清單? – SO44

+0

您應該在字符串上使用'json.loads()'。這將返回一個更簡單,更高效的字典。 – IanAuld

回答

0

我的解決方案是基於您試圖通過詞典列表進行搜索的假設,因此我已經更正了列表。如果列表中的字典不包含您正在搜索的密鑰,則還會出現錯誤。爲此,我爲該函數添加了簡單的錯誤處理。

我是一個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) 

我希望別人能幫助您與任何後續問題,因爲我沒有足夠的積分,使用註釋功能。

0

作爲另一個答案,我添加一個基於假設的解決方案,您的列表是一個字符串的元素,在這種情況下,您最初的發佈列表不需要更正。

# -*- coding: utf-8 -*- 

# Your example list 
myListOfDicts = ['{"activities":[{"activity":"111","interface":"eds","clientIp":"12.207.212.130","logTime":1469811993000},{"activity":"121","dbCount":33,"totalHits":24,"query":"TI', 'the', 'plague","searchedFrom":"Unknown","searchType":"And","logTime":1469811994000}],"session":-2147479722,"customerId":"s8905647","groupId":"main","activity":"111"}'] 

sanitizedList = str(myListOfDicts).replace('"', '') # Convert the list to string and emove double-quotes for simpler search 

activityOne = 'activity:111,' # Set the search pattern for string 1 
activityTwo = 'activity:121,' # Set the search pattern for string 2 
foundFirst = False # Initialize status of whether the first string was found 

search111 = sanitizedList.find(activityOne) # Check position of activity 111 
search121 = sanitizedList.find(activityTwo) # Check position of activity 121 

# Set status of foundFirst to True if activity 111 was found 
if search111 > 0: 
    foundFirst = True 

# If activity 111 was found before activity 121, you can print 
if foundFirst and search111 < search121: 
    print 'Now you can write to file' 

我很好奇,你正在試圖做的究竟是,因爲解決問題的方法很簡單。我假設你正在動態創建列表,在這種情況下,你已經知道在活動121之前是否添加了活動111,並且可以基於此來採取行動。

無論如何,我希望這有助於。

+0

這是很好的解決方案,刪除雙引號是偉大的,並將列表轉換爲字符串是我沒有想到的,仍然是一個初學者..我基本上有一個文件3。500萬行和你在myListOfDicts中添加的行只是其中的1行,我不得不遍歷那個龐大的文件,並且只在存在活動121的地方獲取行,然後是隨後的活動115/116,我可以找到線索從你的代碼..謝謝一噸 –

+0

我也有另一個難題要解決,現在我有200,000行類似於這裏: –

相關問題