我有一个包含以下详细信息的文件:
**169.254.230.157 : 169.254.42.146**
169.254.230.157 : 169.254.138.97
169.254.230.157 : 169.254.162.67
169.254.223.76 : 169.254.42.146
**169.254.223.76 : 169.254.138.97**
169.254.223.76 : 169.254.162.67
我需要获得如下所示的独特线条
169.254.230.157 : 169.254.42.146
169.254.223.76 : 169.254.138.97
以下是我的尝试:
ping_ip = open("ping.txt","r")
ping_lines = ping_ip.readlines()
list1 = []
list2 = []
for line in ping_lines:
ip_s, ip_d = line.split(":")
#print ip_s, " : ", ip_d
m = re.search(ip_s.rstrip(),line)
n = re.search(ip_d.rstrip(),line)
if m and n not in list1 and list2 :
list1.append(m.group(0))
list2.append(n.group(0))
print line
print set(list1)
答案 0 :(得分:0)
看起来你正在寻找独特的组合(即两个项目都没有添加)。你应该更清楚你对唯一的定义:
r = []
with open(...) as f:
seen = set()
for line in f:
x = line.strip().split(' : ')
if all(i not in seen for i in x):
r.append(line.strip())
seen |= set(x)
r
输出:
['169.254.230.157 : 169.254.42.146', '169.254.223.76 : 169.254.138.97']
答案 1 :(得分:-1)
我不确定我是否完全理解您的问题,但如果您尝试从列出的值(例如您列出的IP地址)中获取唯一值,则可以将数据放入Set中,根据定义,该集合是独特的物品。
https://docs.python.org/2/library/sets.html
使用您的代码,您可以执行以下操作(不确定这是否有效,但仅用于演示目的):
from sets import Set
### - print IPs - ###
ping_ip = open("ping.txt","r")
ping_lines = ping_ip.readlines()
count = 0
print "################################################"
print "START"
print "################################################"
try:
#####
set1=Set()
set2=Set()
for line in ping_lines:
ip_s, ip_d = line.split(":")
set1.add(ip_s)
set2.add(ip_d)
print set(list1)
print set(list2)
#####
except:
print "exiting..."