[英]Compare multiple items in a list of tuples and deleting tuples from the same list
[英]compare items in the same list
我有一個格式的配置文件:
IP,用戶名,日志文件
IP,用戶名,logfile1
IP,用戶名,logfile2
我在下面提供代碼以將文本文件行存儲到列表中,但是我需要代碼方面的幫助,該代碼可以確定日志文件的名稱與logfile1是否相同,請幫助
import csv
config_file_path = "config15.txt" # read config file and assign IP,username,logfile,serverpath,localpath
file = open(config_file_path, 'r')
reader = csv.reader(file)
all_rows = [row for row in reader] # appending config file contents in a list
上面的代碼輸出給出:
[['127.0.0.1', 'new34', 'logfile'], ['127.0.0.1', 'new34', 'logfile1']]
我想要一個比較並告訴logfile
和logfile1
名稱是否相同以及輸出是否返回true的代碼。
使用一個簡單的迭代並將一個set
用作檢查變量。
例如:
all_rows = [['127.0.0.1', 'new34', 'logfile1'], ['127.0.0.1', 'new34', 'logfile1']]
def check_row(data):
seen = set()
for i in data:
if i[-1] in seen:
return True
else:
seen.add(i[-1])
return False
print(check_row(all_rows)) #True
如果這確實是您的文件格式。 將其讀取為數據框會更容易:
import pandas as pd
df = pd.read_csv('config15.txt',sep=',', header = None, names =['ip','un','lf']) #or just change extension to *.csv
dupldf =df[df.duplicated(['lf'])]# find duplicate rows
如果為空,則沒有重復的值
因此,據我了解,您正在尋找日志文件重復項。 首先,您需要一個列表(或日志文件的向量),例如:
logfiles = [row[-1] for row in reader]
此列表包含日志文件名稱。 現在,我建議您使用numpy
,這是一個非常大的python庫,其中包含有用的方法(如果要在python中編寫代碼,則必須了解此庫),因此:
import numpy as np
logfiles = np.array(logfiles) #simply transformation of list into a numpy array
i, j = np.where(logfiles[:, np.newaxis]==logfiles[np.newaxis, :])
logfiles[i]
是重復的元素,即logfiles[i] = logfiles[j]
顯然每個元素也都等於它自己,因此您必須刪除i==j
的元素:
index2save = np.where(i[:, np.newaxis]!=j[np.newaxis, :])[0]
i = i[index2save]
現在, i
是重復元素的索引,而logfiles[i]
是相同的名稱。 希望對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.