2016-08-05 8 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"が発生した後、このリストに存在する場合にのみ、この全体のリストを書きたいです。この例のように、1番目の"activity":"111"が存在し、後で"activity":"121"も存在します。このリストをファイルと任意のリストに書きたいと思います。"activity":"111"の後ろには"activity":"121"が続かないので、書きたくありません。

どうすればよいですか?助けてください。

+1

このリストは辞書のような文字列を持つ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'はアクティビティ111の後でアクティビティ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

もう1つの回答として、あなたのリストが文字列の1つの要素であるという前提に基づいて解決策を追加しています。この場合、最初に投稿されたリストには修正が必要ありません。

# -*- 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' 

私はあなたの問題を解決するには非常に簡単ですので、それは、あなたがやろうとしているです正確に何をするように興味があります。私はあなたが動的にリストを作成していると仮定します。その場合、アクティビティー111がアクティビティー121の前に追加されていて、それに基づいてアクションを取ることができます。

とにかく、私はこれが役立つことを願っています。

+0

これは素晴らしい解決策です。二重引用符を削除することは素晴らしく、リストを文字列に変換することは、私が考えなかったものでした。まだ初心者です。私は基本的に3つのファイルを持っています。500万行とmyListOfDictsで追加した行は、その行のうちの1行だけです。その巨大なファイルを実行して、アクティビティ121が存在する行だけを取得し、それに続いてアクティビティ115/116を実行しなければなりませんでした。あなたのコードから..感謝します –

+0

私は解決する別のパズルを持って、今私はここに1つに似た200,000行があります: –