需要关于Python脚本的帮助,因为我对此完全陌生!
我有两个文本文档,如下所示,想看看文件1中列A上的元素是否存在于文件2中列A的某个位置。列用TAB分隔。其他列上的文本无关紧要。
File1
1 test
4 sample
10 abc
7 text
File2
2 abs
10 abj
1 test
32 python
并且期望的输出将是
1
10
def get_col1_elems(file_name):
with open(file_name, 'r') as f:
return [line.split()[0] for line in f.readlines()]
for item in [i for i in get_col1_elems('file1.txt') if i in get_col1_elems('file2.txt')]:
print(item)
要求的用于解释目的的详细版本
def get_col1_elems(file_name):
col1_elems = []
with open(file_name, 'r') as f:
for line in f.readlines():
all_line_elements = line.split()
first_line_element = all_line_elements[0]
col1_elems.append(first_line_element)
return col1_elems
file1_list = get_col1_elems('file1.txt')
file2_list = get_col1_elems('file2.txt')
items_in_both_lists = []
for i in file1_list:
if i in file2_list:
items_in_both_lists.append(i)
for items in items_in_both_lists:
print(item)