2016-08-05 5 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

내 솔루션은 사전 목록을 검색하려고한다는 가정하에 작성되었으므로 목록을 이와 같이 수정했습니다. 목록에있는 사전에 검색중인 키가 포함되어 있지 않으면 오류가 발생합니다. 그 목적을 위해 함수에 간단한 오류 처리를 추가했습니다.

저는 파이썬 초보자입니다. 따라서 제게는보다 우아한 해결책이 존재할 수 있지만, 필요한 것이면 충분할 수 있습니다. 그것은 다음과 같이 작동합니다 : '111'값을 가진 키 'activity'의 발생이 발견되면, 나머지리스트는 'value 121'키로 'activity'키의 발생을 검색합니다. 충분히 간단합니다. 또한,

if i[key] == valueTwo and foundOne and (dictCount - 1) == countHelp: 

: 경우

은, 그러나, 당신은 단지 조건 활동 (121) 활동 (111)의 발생 후 바로 다음 사전에 발견되면, 당신은 단순히 라인 (14)이 변경할 수 있습니다 만났다 고려 나는 당신이 액티비티 111 후에 액티비티 121이 처음 발견 된 사전을 쓰려고하는지, 아니면 사전의 전체리스트를 쓰고 싶다면 확실하지 않다. 변수 'myDictionaries'는 전체 목록이고, 변수 'i'는 활동 121 후에 활동 121이 발견 된 첫 번째 사전입니다.

내 솔루션에서는 글을 쓰지 않고 목록을 인쇄합니다 파일로. 따라서 파일 쓰기 솔루션으로 변경하십시오.

# -*- 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이 활동 121보다 먼저 추가되고 이에 따라 조치를 취할 수있는 경우 이미 알 수 있습니다.

어쨌든 도움이 되길 바랍니다.

+0

이것은 훌륭한 해결책입니다. 큰 따옴표를 제거하고 문자열을 문자열로 변환하는 것은 제가 생각하지 못했던 초보자입니다. 기본적으로 3 개의 파일이 있습니다.5 백만 라인과 myListOfDicts에 추가 한 라인은 그 라인 중 단지 하나 일뿐입니다. 그 거대한 파일을 조사하고 액티비티 121이 존재하는 곳에서만 줄을 긋고 그 다음으로 115/116 액티비티를 따라야했습니다. 당신의 코드에서. 감사합니다. –

+0

해결할 또 다른 퍼즐이 있습니다. 이제 여기에 비슷한 200,000 개의 라인이 있습니다. –