在 Python 3 中打开 2 个文件并将它们分配给 2 个集合

Dgu*_*gun 2 python file set

这是我的示例代码。有用。但我确信有一种更简单的方法可以将值存储在集合中。我只知道如何先将它们存储在一个列表中,然后将它们转移到一个集合中。我将它们移动到集合中的原因是利用差异()方法。只是向社区寻求一些建议。大家的意见都很好!

a_file = open(r'c:\a.csv', 'r')
b_file = open(r'c:\b.csv', 'r')

a_list = a_file.read().splitlines()
b_list = b_file.read().splitlines()

a_file.close()
b_file.close()

"""
Here, I am declaring 2 sets and then clear them of their 
values before storing the values from the lists.  
If I didn't do it this way, Python would think these were 
DICTIONARY datatypes instead and produce an syntax error.
"""

a_set = {1} #Just to get the program to recognize it as a set.
b_set.clear() #Then clear the data so that it is empty but stays as a set datatype.
a_set = {1}
b_set.clear()

a_set.update(a_list)
b_set.update(b_list)

difference_list = a_set.difference(b_set)
Run Code Online (Sandbox Code Playgroud)

C14*_*14L 5

只需环绕set()列表。

def readfile(fn):
    with open(fn, 'r') as fh:
        return fh.read().splitlines()

diff = set(readfile("file1.txt")).difference(set(readfile("file2.txt")))
Run Code Online (Sandbox Code Playgroud)

  • `.difference()` 方法会自动将 Iterable 转换为集合。因此,您可以将最后一行简化为 `diff = set(readfile("file1.txt")).difference(readfile("file2.txt"))`。 (2认同)