gpt4 book ai didi

python - 按公共(public)列合并两个表

转载 作者:太空宇宙 更新时间:2023-11-03 19:08:13 24 4
gpt4 key购买 nike

假设我有两个文件,有数据

table1.txt内容

avvd, 1234, ufgh
klpn, 5678, oppr
srtv, 9abc, pxyz

table2.txt内容

abcd, 1234, efgh
klmn, 5678, opqr
stuv, 9abc, wxyz

现在我想合并它们,因为它们的第二列是相同的,并显示结果。

所需的输出是如果 table1.txt 和 table2.txt 列相同,则合并两个表并使它们成为一个并在输出中显示它们

avvd, 1234, ufgh, abcd, efgh
klpn, 5678, oppr, klmn, opqr
srtv, 9abc, pxyz, stuv, wxyz

最佳答案

#input

file1 = open('1.txt', 'r')
file2 = open('2.txt', 'r')
matrix1 = [line.rstrip().split(', ') for line in file1.readlines()]
matrix2 = [line.rstrip().split(', ') for line in file2.readlines()]
file1.close()
file2.close()

#combine

t_matrix1 = [[r[col] for r in matrix1] for col in range(len(matrix1[0]))]
t_matrix2 = [[r[col] for r in matrix2] for col in range(len(matrix2[0]))]
final_t_matrix = []
for i in (t_matrix1 + t_matrix2):
if i not in final_t_matrix:
final_t_matrix.append(i)
final_matrix = [[r[col] for r in final_t_matrix] for col in range(len(final_t_matrix[0]))]

#output

outfile = open('out.txt', 'w')
for i in final_matrix:
for j in i[:-1]:
outfile.write(j+', ')
outfile.write(i[-1]+'\n')
outfile.close()

关于python - 按公共(public)列合并两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13932375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com