首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在python中获得以下输出

如何在python中获得以下输出
EN

Stack Overflow用户
提问于 2018-08-16 04:17:03
回答 1查看 57关注 0票数 -1

我正在尝试比较两个有子网的文本文件,并能够得到输出。但我需要正确格式的输出(逐行)。我还想添加一条print语句作为"Match in the both lists“。

目前,我得到的输出如下:

代码语言:javascript
复制
2.144.0.0/142.176.0.0/12root@vagrant-ubuntu

我的预期输出:

代码语言:javascript
复制
Match in both the lists
2.144.0.0/14
2.176.0.0/12
root@vagrant-ubuntu

代码

代码语言:javascript
复制
#Open the first file and read in each line as
#a value in a list called lines1. After reading
#each line, then strip off any extra whitespace
#or typeset characters.
with open('6output.txt') as f1:
    lines1 = f1.readlines()
    lines1 = [x.strip() for x in lines1]
f1.close()
#Open the second file and read in each line as
#a value in a list called lines2. After reading
#each line, then strip off any extra whitespace
#or typeset characters.
with open('7subnet.txt') as f2:
    lines2 = f2.readlines()
    lines2 = [x.strip() for x in lines2]
f2.close()
#Loop over each element in the two lists. If a
#match is found, then we write the value to the
#output file. If there is no match, output info.
test = 0
fileout = open('9output.txt', 'w')
for val1 in lines1:
    for val2 in lines2:
        if val1 == val2:
            fileout.write(val1)
test = 1
fileout.close()
if test == 0:
    print("No matches found!")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-16 04:34:26

检查这是否起作用。要在不同的行中编写代码,可以使用"\n"。和id如果你只想在两个列表中放一次"Match in the lists“,你就需要另外放一条if语句。

代码语言:javascript
复制
test = 0
fileout = open('9output.txt', 'w')
for val1 in lines1:
    for val2 in lines2:
        if val1 == val2:
            if test == 0:
                fileout.write("Match in both the lists")
                fileout.write(val1+"\n")
                test = 1
            else:
                fileout.write(val1+"\n")
fileout.close()
if test == 0:
    print("No matches found!")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51865819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档