How to create a list in Python with the unique values of a CSV file?

前端 未结 3 750
长发绾君心
长发绾君心 2020-12-06 17:38

I have CSV file that looks like the following,

1994, Category1, Something Happened 1
1994, Category2, Something Happened 2
1995, Category1, Something Happen         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 17:50

    You can do:

    DataCaptured = csv.reader(DataFile, delimiter=',', skipinitialspace=True) 
    
    Category, Year = [], []
    for row in DataCaptured:
        if row[0] not in Year:
            Year.append(row[0])
        if row[1] not in Category:
            Category.append(row[1])    
    
    print Category, Year        
    # ['Category1', 'Category2', 'Category3'] ['1994', '1995', '1996', '1998']
    

    As stated in the comments, if order does not matter, using a set would be easier and faster:

    Category, Year = set(), set()
    for row in DataCaptured:
        Year.add(row[0])
        Category.add(row[1])
    

提交回复
热议问题