我有这样的代码:
chain = '>'
contain=''
file = raw_input('Enter your filename : ')
fileName = open(file,'r')
for line in fileName:
if chain in line :
pass
if not(chain in line):
contain+=line
print contain
fileName.close()
这个file.txt:
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming.
It features a dynamic type system and automatic memory management.
He has a large and comprehensive standard library我得到了“打印”的结果:
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming.
It features a dynamic type system and automatic memory management.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming.
It features a dynamic type system and automatic memory management.
He has a large and comprehensive standard library为什么我有副本?
发布于 2015-04-26 22:43:34
在循环的每一次迭代中,当:
if not(chain in line):
contain+=line
print(contain)因为您连接了contain中的每一行,所以当您打印它时,它将显示第一个句子,第一个迭代,然后是第二个迭代中的first+second语句,依此类推。因此出现了重复。
将print(contain)替换为print(line)将不重复地打印行。
发布于 2015-04-26 22:44:16
在第一次迭代之后,将文件的第一行添加到contain中,然后打印出来。
在第二次迭代之后,将文件的第二行添加到contain,其中仍然包含第一行,然后打印它。
第三次迭代也是如此。
您正在看到副本,因为您多次打印contain,并且其中包含前面的行。
https://stackoverflow.com/questions/29884453
复制相似问题