Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python比较文件A和B中的值的方法,如果A匹配,则打印B中的整行_Python_Python 3.x - Fatal编程技术网

Python比较文件A和B中的值的方法,如果A匹配,则打印B中的整行

Python比较文件A和B中的值的方法,如果A匹配,则打印B中的整行,python,python-3.x,Python,Python 3.x,我有两个文本文件: myfile1: sports1 sports2 sports3 sports4 sports5 sports6 sports7 sports8 myfile2: sports1 Cricket sports2 golf sports3 Hocky sports4 sports5 Chess sports6 Snooker sports7 Foosball sports8 Tampts 从上面的两个文件中,fmyfile1中的第一列与myfile2中的第一列

我有两个文本文件:

myfile1:

sports1
sports2
sports3
sports4
sports5
sports6
sports7
sports8
myfile2:

sports1  Cricket
sports2  golf
sports3  Hocky
sports4
sports5  Chess
sports6  Snooker
sports7  Foosball
sports8  Tampts
从上面的两个文件中,f
myfile1
中的第一列与
myfile2
中的第一列匹配,然后它应该打印
myfile2
的两列

下面的awk one行程序可以工作,但我正在Python中寻找一个类似的行程序

awk 'NR==FNR{c[$1]++;next};c[$1]' myfile1 myfile2

如果愿意,您可以使用第三方库,如Pandas。这可能是最接近你的一个班轮

delim_whitespace=True
确保Pandas使用空格分隔列,而不是常规csv中的

import pandas as pd

df1 = pd.read_csv('file1.txt', header=None, names=['sport'])
df2 = pd.read_csv('file2.txt', header=None, names=['sport', 'name'],
                  delim_whitespace=True)

res = df2[df2['sport'].isin(df1['sport'].unique())]

print(res)

作为一种选择,您可以对列表和字典执行相同的操作。考虑到这一点,您可以在理解中打开文件,执行后这些文件将被关闭。尽管完成此类任务的最佳方法是使用“with”作为上下文管理器

f1 = [x.strip("\n") for x in open("myfile1.txt")].sort()
f2 = {x[0]: x[1] for x in [l.split() for l in open("myfile2.txt")]}
if f1 == list(f2.keys()).sort():
    [print(k, v) for k, v in f2.items()]

这是一个很好的答案。但是,对于替代解决方案,它给出了索引错误<代码>回溯(最后一次调用):文件“/user\u group\u identifier4.py”,第4行,在f2={x[0]:x[1]中为x在[l.split()中为l在open中(“file2.txt”)]}文件“/user\u group\u identifier4.py”,第4行,在f2={x[0]:x[1]中为x在[l.split()中为l在open中(“file2.txt”)}索引器:列表索引超出范围