[英]How do you ensure that each unique line printed once in python
我如何確保每個唯一的行在python中僅打印一次:
我正在連接到Oracle數據庫並檢索一些記錄。 可以從數據庫中兩次或多次獲取具有准確時間戳,值等的相同記錄。 我來自R編程,可以在其中向數據幀發出唯一命令以完成此任務。
我如何確保每個唯一字段在pyton中僅打印一次。 這是我的代碼:
import pyodbc
import re
sql="DateTime, Server, Server_Type, Metric, Value from oracle_table"
cnxn = pyodbc.connect("DSN=dsn1;UID=userid;PWD=passwd123")
cursor = cnxn.cursor()
cursor.execute(sql)
row = cursor.fetchall()
for line in row:
if line[4]:
if float(line[4])>=0:
print line[1]+"."+re.sub(r'\W+', '', re.sub(r'\%', 'Percent', line[3])),line[0].strftime('%s'), ("%.6f" % float(line[4])), "host="+re.sub("\..*$","",line[1]), "type="+line[2],"source=Oracle","dc=DC1"
輸出為:
server1.CRITICAL_INCIDENTS 1418223897 0.000000 host=server1 type=oracle_database source=Oracle dc=DC1
server1.ResponseTimepertransaction 1418223577 2.467900 host=server1 type=oracle_database source=Oracle dc=DC1
server1.DataDictionaryHitPercent 1418223577 100.000000 host=server1 type=oracle_database source=Oracle dc=DC1
server1.FullIndexScanspersecond 1418223577 0.000000 host=server1 type=oracle_database source=Oracle dc=DC1
server1.ExecutesPerformedwithoutParsesPercent 1418223577 66.666667 host=server1 type=oracle_database source=Oracle dc=DC1
server1.SortsinMemoryPercent 1418223577 100.000000 host=server1 type=oracle_database source=Oracle dc=DC1
server1.BufferCacheHitPercent 1418223577 100.000000 host=server1 type=oracle_database source=Oracle dc=DC1
server1.DatabaseCPUTimePercent 1418223577 81.048665 host=server1 type=oracle_database source=Oracle dc=DC1
server1.CRITICAL_INCIDENTS 1418223897 0.000000 host=server1 type=oracle_database source=Oracle dc=DC1
server1.CRITICAL_INCIDENTS 1418223897 0.000000 host=server1 type=oracle_database source=Oracle dc=DC1
server1.ResponseTimepertransaction 1418223577 2.467900 host=server1 type=oracle_database source=Oracle dc=DC1
# Python 2.7
seenAlready = set()
for line in row:
if line[4]:
if float(line[4])>=0:
outputLine = ... # Whatever you do to construct the output line
if outputLine not in seenAlready:
print outputLine
seenAlready.add(outputLine)
ll=[]
for line in row:
if line[4]:
if float(line[4])>=0:
ll.append(line[1]+"."+re.sub(r'\W+', '', re.sub(r'\%', 'Percent', line[3])),line[0].strftime('%s'), ("%.6f" % float(line[4])), "host="+re.sub("\..*$","",line[1]), "type="+line[2],"source=Oracle","dc=DC1")
print set(ll)
您可以在這里使用set
。
在SQL查詢中使用select unique。
import pyodbc
import re
sql = """select distinct DateTime, Server, Server_Type, Metric, Value
from oracle_table where Value >= 0"""
cnxn = pyodbc.connect("DSN=dsn1;UID=userid;PWD=passwd123")
cursor = cnxn.cursor()
cursor.execute(sql)
row = cursor.fetchall()
for line in row:
print line[1]+"."+re.sub(r'\W+', '', re.sub(r'\%', 'Percent', line[3])),
line[0].strftime('%s'), ("%.6f" % float(line[4])),
"host="+re.sub("\..*$","",line[1]),
"type="+line[2],"source=Oracle","dc=DC1"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.