gpt4 book ai didi

python - 基于 if 循环合并两个列表的内容

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:54 25 4
gpt4 key购买 nike

我在检查列表中的元素时遇到一个小问题:我有两个文件,内容类似这样

file 1:        file2:
47 358 47
48 450 49
49 56 50

我将这两个文件解析成两个列表,并使用以下代码进行检查

for i in file_1:
for j in file_2:
j = j.split()
if i == j[1]:
x=' '.join(j)
print >> write_in, x

如果 file_1 的值不在 file_2 中,我现在试图得到一个“0”,例如,值“48”不存在 file_2,所以我需要得到类似的输出(中间只有一个空格这两个数字)而且这两个条件都应该只产生一个输出文件:

output_file:
358 47
0 48
450 49
56 50

我尝试使用字典方法,但我并没有完全得到我想要的(实际上我不知道如何在 python 中正确使用字典;))。任何帮助都会很棒。

最佳答案

r1=open('file1').read().split()
r2=open('file2').read().split()

d=dict(zip(r2[1::2],r2[::2]))

output='\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)

open('output_file','wb').write(output)

测试

>>> file1='47\n48\n49\n50'
>>> file2='358 47\n450 49\n56 50'
>>>
>>> r1=file1.split()
>>> r2=file2.split()
>>>
>>> d=dict(zip(r2[1::2],r2[::2])) #
>>> d
{'47': '358', '50': '56', '49': '450'}
>>>
>>> print '\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)
358 47
0 48
450 49
56 50
>>>

关于python - 基于 if 循环合并两个列表的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2507090/

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