擅长:python、mysql、java
<p>可以使用<a href="https://docs.python.org/3.4/library/collections.html#collections.Counter" rel="nofollow">Counter</a>,然后只打印值为2的项。由于打开的文件是可iterable的(即使用for循环时可以遍历行),因此可以直接对打开的文件调用<code>Counter</code>:</p>
<pre><code>from collections import Counter
with open('file1') as file1, open('file2') as file2:
ids = Counter(file1)
ids.update(file2)
for key, value in ids.items():
if value > 1:
print(key)
</code></pre>
<p>此方法将包括尾随的换行符。很可能这不是您想要的;如果是这样,则必须显式迭代文件并显式删除空白:</p>
<pre><code>from collections import Counter
with open('file1') as file1, open('file2') as file2:
ids = Counter()
for line in file1:
ids.update([line.strip()])
for line in file2:
ids.update([line.strip()])
for key, value in ids.items():
if value > 1:
print(key)
</code></pre>