Python:将列表与文件中的列表进行比较

Python:将列表与文件中的列表进行比较,python,file,list,Python,File,List,我正在努力解决这个看起来很简单的问题,但我被卡住了!嗯,我必须构建一个函数,在该函数中我会收到一个类别列表,如: input Example1: ['point_of_interest', 'natural_feature', 'park', 'establishment'] input Example2: ['point_of_interest', 'establishment'] input Example3: ['sublocality', 'political'] 所以这个列表里面可能

我正在努力解决这个看起来很简单的问题,但我被卡住了!嗯,我必须构建一个函数,在该函数中我会收到一个类别列表,如:

input Example1: ['point_of_interest', 'natural_feature', 'park', 'establishment']
input Example2: ['point_of_interest', 'establishment']
input Example3: ['sublocality', 'political']
所以这个列表里面可能有变量元素,我猜从1到4不等

因此,使用相同的数据,我将使用该输入创建一个文件,如果新输入不在文件中,则将其附加到文件中

每个列表本身就是一个元素,我的意思是我必须比较列表的所有元素,如果我能找到其他完全相同的列表,我就不必添加它

在我的代码中,我只是尝试在文件中添加第一个元素,因为我真的不知道如何添加完整列表与下一个列表进行比较

def categories(category):
    number = 0
    repeat = False
    if os.path.exists("routes/svm/categories"):
        with open('routes/svm/categories', 'rb') as csvfile:
            spamreader = csv.reader(csvfile)
            for categoryFile in spamreader:
                if (cmp(categoryFile,category) == 0):
                    number += 1
                    repeat = True
                if not repeat:
                    categoriesFile = open('routes/svm/categories', 'a') 
                    category = str(category[0])     
                    categoriesFile.write(category) 
                    categoriesFile.write('\n')
                    categoriesFile.close()
                else:
                    categoriesFile = open('routes/svm/categories', 'w')
                    category = str(category[0])     
                    categoriesFile.write(category)
                    categoriesFile.write('\n')
                    categoriesFile.close()      

编辑:@KlausWarzecha的一些解释:用户可能会输入一个包含(大约4)项的列表。如果此列表(=此项目组合)不在文件中,是否要将列表(而不是单独的项目!)添加到文件中

问题真的很简单。如果对您有效,您可以采用以下方法:

  • 将CSV的所有内容读取到列表中
  • 将输入中的所有不匹配项添加到此列表中
  • 重新写入CSV文件
  • 您可以从以下示例代码开始:

    # input_list here represents the inputs
    # You may get input from some other source too
    input_list = [['point_of_interest', 'natural_feature', 'park', 'establishment'], ['point_of_interest', 'establishment'], ['sublocality', 'political']]
    category_list = []
    with open('routes/svm/categories', 'rb') as csvfile:
        spamreader = csv.reader(csvfile)
        for categoryFile in spamreader:
            print categoryFile
            category_list.append(categoryFile)
    for item in input_list:
        if (item in category_list):
            print "Found"
        else:
            category_list.append(item)
            print "Not Found"
    
    # Write `category_list` to the CSV file
    
    请将此代码用作起点,而不是复制粘贴解决方案


    为什么不能将所有元素逐个写入文件?你的问题对我来说很难理解me@MichaelButscher我在我的函数中收到了一个列表,我必须与文件中的列表进行比较,如果这个新列表不在文件中,我必须添加它,基本上这就是问题所在。对不起,我的英语很难理解你的问题。你想得到一个唯一元素的列表并将它们写入文件吗?@taonico好的,为什么你不能将for循环中的所有列表元素(而不仅仅是第一个)写入文件?@theghosfc就好像输入列表只是一个列表而不是一个列表list@taonico,输入只是一个列表。那么,上面提到的例子在3次不同的程序运行中显示了3个不同的输入?此外,数据如何存储在CSV文件中。只有一列还是多列?您能否共享CSV文件中的2-3个示例记录,以便更好地理解?