我有一个类似这样的列表...
data = [['09/10/2018', '11/10/2018', 'Subject A', 'Teacher Name A', 'Assignment text...'], ['09/10/2018', '10/10/2018', 'Subject B', 'Teacher Name B', 'Assignment text...']]
我想从该列表中删除前三个元素位于.csv文件中的每个元素。
CSV示例:
09/10/2018, 11/10/2018, Subject A
09/10/2018, 10/10/2018, Subject B
24/09/2018, 01/10/2018, Subject E
此.csv可能包含与数据列表中的任何列表都不匹配的行。
我的问题是我无法基于.csv从数据列表中成功删除列表
以下是相关代码:
data = pull_data() # Gets the list of lists
with open('Log.csv') as f: #Opens Log.csv
prevData=[tuple(line) for line in csv.reader(f)] #Gets the data from the .csv
for sublist in data:
for prevSub in prevdata:
if(len(sublist) > 0 and len(prevSub) > 0):
if sublist[0] == prevSub[0]:
if sublist[1] == prevSub[1]:
if sublist[2] == prevSub[2]
data.pop(data.index(sublist)) # Should remove list from list of lists
答案 0 :(得分:1)
这是一种方式。这个想法是从csv文件构造一组元组。然后使用列表推导来过滤data
。这样可以确保O(1)查找的复杂性。由于tuple
是可哈希的,而list
不是可哈希的,因此必须进行元组转换。
from io import StringIO
import csv
data = [['09/10/2018', '11/10/2018', 'Subject A', 'Teacher Name A', 'Assignment text...'],
['09/10/2018', '10/10/2018', 'Subject B', 'Teacher Name B', 'Assignment text...']]
x = StringIO(""" 09/10/2018, 11/10/2018, Subject A
09/10/2018, 10/10/2018, Subject B
24/09/2018, 01/10/2018, Subject E""")
# replace x with open('Log.csv')
with x as fin:
set_of_tuples = set(map(tuple, csv.reader(fin, skipinitialspace=True)))
# apply filter
res = [i for i in data if tuple(i[:3]) not in set_of_tuples]