这是我的示例代码。有用。但我确信有一种更简单的方法可以将值存储在集合中。我只知道如何先将它们存储在一个列表中,然后将它们转移到一个集合中。我将它们移动到集合中的原因是利用差异()方法。只是向社区寻求一些建议。大家的意见都很好!
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)
只需环绕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)
| 归档时间: |
|
| 查看次数: |
31 次 |
| 最近记录: |