合并内容,如果环
我有一个小问题,而检查列表中的元素: 我有两个文件的内容是这样的合并内容,如果环
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
我现在正在试图获得一个“0”,如果file_1的价值是不存在的file_2例如,值“48”是不是有一种file_2所以我需要得到输出像(两个数字之间只有一个空格)也是两个Ë条件应该产生只有一个输出文件:
output_file:
358 47
0 48
450 49
56 50
我尝试使用字典方法,但我并没有完全得到我想要的东西(其实我不知道使用的字典如何在Python正确;))。任何帮助都会很棒。
你可以很容易地修改代码:
for i in file_1:
x = None
for j in file_2:
j = j.split()
if i == j[1]:
x = ' '.join(j)
if x is None:
x = ' '.join(['0', i])
根据你的投入,整个任务可能是当然进一步简化。目前,你的代码是0(n**2)
的复杂性。
其实它是O(N + M)。您只需要对每个文件进行顺序扫描。 – tzot 2010-03-27 00:03:50
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
>>>
下面是一个使用字典中的可读的解决方案:
d = {}
for k in file1:
d[k] = 0
for line in file2:
v, k = line.split()
d[k] = v
for k in sorted(d):
print d[k], k
将字典初始化为某个值最好用'完成。fromkeys' classmethod。 – SilentGhost 2010-03-24 15:29:53
你可以尝试这样的:
l1 = open('file1').read().split()
l2 = [line.split() for line in open('file2')]
for x, y in zip(l1, l2):
if x not in y:
print 0, x
print ' '.join(y)
,但如果你按照你的逻辑,输出应该是
358 47
0 48
450 49
0 49
56 50
和不
358 47
0 48
450 49
56 50
def file_process(filename1, filename2):
# read first file with zeroes as values
with open(filename1) as fp:
adict= dict((line.rstrip(), 0) for line in fp)
# read second file as "value key"
with open(filename2) as fp:
adict.update(
line.rstrip().partition(" ")[2::-2] # tricky, read notes
for line in fp)
for key in sorted(adict):
yield adict[key], key
fp= open("output_file", "w")
fp.writelines("%s %s\n" % items for items in file_process("file1", "file2"))
fp.close()
str.partition(”“)返回(预空间,空间,空间柱)的元组。通过对元组进行切片,从项目2(后空间)开始,并以-2的步长移动,我们返回(后空间,预空间)的元组,它们是(字典,值)解决方案。
PS嗯:)我刚刚注意到我的答案基本上与Daniel Stutzbach的相同。
这不是一个有效的python – SilentGhost 2010-03-24 11:10:04
你有没有试过保留其他语句? else x ='0'.join(j) – 2010-03-24 11:10:41
数字(file1中的数字和file2中的第二个数字)总是按顺序排列?按字母顺序还是数字顺序?他们是否总是数字?输出文件是否需要按顺序排列? – 2010-03-24 11:49:13