2016-08-15 3 views
1

重複するデバイス名を持つ行をCSVファイルで検索しようとしています。出力には、最初に一致する行の日付が記録され、見つかった最後の行の日付も記録されます。 CSVファイルから重複したデバイス名を取り除くロジックを援助する必要があります。同時に、デバイスが最初に見られたときと最後に見たときの記録を保持します。一致するフィールドのCSVを検索し、初期日付を使用します。

import time as epoch 

# AlertTime, DeviceName, Status 
Input = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']] 

# FirstSeen, LastSeen, DeviceName, Status 
Output = [] 

# Last 48 hours 
now = epoch.time() 
cutoff = now - (172800) 

for i in Input: 
    AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M')) 
    if AlertTime > cutoff: 
     Result = [i[0], i[0], i[1], i[2]] 
     Output.append(Result) 

print(Output) 

出力(3エントリー):

[['14/08/2016 13:00', '14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', '15/08/2016 17:30', 'device-A', 'UP']] 

募集出力(2エントリー):Vedangメータはコメントで言ったように

[['14/08/2016 13:15', '14/08/2016 13:15', 'device-B', 'DOWN'], ['14/08/2016 13:00', '15/08/2016 17:30', 'device-A', 'UP']] 
+1

使用辞書を、ステータス)を値として返します。 –

+0

@VedangMehtaおそらくあなたは既にキーであるので、 'DeviceName'フィールドを省略することができますか?そうでなければ、私は完全に同意する。 – bdvll

+0

@bdvllあなたは絶対に正しいです。 –

答えて

1

OrderedDictを使用すると、CSVファイルにデバイスが表示される順序を維持できます。辞書は重複を自動的に削除するために使用されます。

既存の辞書エントリを更新しようとすると、以下のように動作します。まだ存在しない場合、PythonはKeyError例外を生成します。この場合、同じ開始時間と終了時間のアラートで新しいエントリを追加できます。エントリを更新する際には、既存のfirst_seenを使用して、最新のエントリがalert_timeおよびstatusに更新されます。あなたは、出力与える

from collections import OrderedDict 

# AlertTime, DeviceName, Status 
input_data = [['14/08/2016 13:00', 'device-A', 'UP'], ['14/08/2016 13:15', 'device-B', 'DOWN'], ['15/08/2016 17:30', 'device-A', 'UP']] 

entries = OrderedDict() 

for alert_time, device_name, status in input_data: 
    try: 
     entries[device_name] = [entries[device_name][0], alert_time, status] 
    except KeyError as e: 
     entries[device_name] = [alert_time, alert_time, status] 

# Convert the dictionary of entries into the required format   
output_data = [[device_name, first_seen, last_seen, status] for device_name, [first_seen, last_seen, status] in entries.items()] 

print(output_data) 

:終了時に、辞書がご必要な出力形式作成するために解析されたキーと `(FirstSeen、LastSeen、DeviceNameのようdevice``と

[['device-A', '14/08/2016 13:00', '15/08/2016 17:30', 'UP'], ['device-B', '14/08/2016 13:15', '14/08/2016 13:15', 'DOWN']] 
+0

ありがとうマーティン、私はあなたの助けに感謝します。私はあなたのアプローチを使用して終了しました。 – zeepi

1

、あなたが保存するために辞書を使用することができますデータ。この後

my_dict = {} 
    for i in Input: 
     AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M')) 
     if AlertTime > cutoff: 
      #if we have seen this device before, update it 
      if i[1] in my_dict: 
       my_dict[i[1]] = (my_dict[i[1]][0], i[0], i[2]) 
      #if we haven't seen it, add it 
      else: 
       my_dict[i[1]] = (i[0],i[0],i[2]) 

、すべてのデバイスは、(first_seenlast_seenstatus)を含むmy_dictに保存されます。

+0

あなたの努力に感謝bdvll – zeepi

関連する問題