Python关于csv读写的小题目笔记

 You are given a spending sheet in a csv file including (name of users, date, spending). User 
names are unique. 
For each user, your task is to 
2.1 Find the dates in which the user spends more than the previous day and the next day. 
2.2 Find the dates in which the user spends more than the 7 days before or the 7 days after.

# coding:utf-8
import csv

csvFilePath = "E:/Desktop/Task2_Expenses_by_client.csv"
personDict = {}     # 存放“人名:对应第一条的序号”的键值对
allItemList = []    # 存放csv内容
allDateList = []    # 存放最终结果

with open(csvFilePath, 'r') as f:
    f_csv = csv.reader(f)
    for row in f_csv:
        allItemList.append(row)                     # 将所有条目放进列表,方便后续处理,无需再次读取文件
        if row[1] not in personDict.keys():         # 将所有人名和对应的序号以键值对形式放入字典,方便后续处理
            personDict[row[1]] = row[0]

    f.close()

# 删除第一行的属性
del personDict['name']
del allItemList[0]
personList = list(personDict.keys())
indexList = list(personDict.values())

# print(allItemList)
print(len(allItemList))
print("\n-------------------------------------------------------------\n")
# print(personDict)
print(len(personDict))
print("\n-------------------------------------------------------------\n")
# print(personList)
print(len(personList))
print("\n-------------------------------------------------------------\n")
# print(indexList)
print(len(indexList))
print("\n-------------------------------------------------------------\n")

for j in range(len(personList)):
    star = int(indexList[j])
    if j == len(personList)-1:
        end = len(allItemList)-1
    else:
        end = int(indexList[j+1])-1
    print("{}:{} -> {}\n".format(personList[j], star, end))

    tempList = [personList[j]]                        # 每个子列表第一个放用户姓名
    for i in range(star+1, end):
        if int(allItemList[i][3]) > int(allItemList[i-1][3]) and int(allItemList[i][3]) > int(allItemList[i+1][3]):
            # 这里直接将符合条件的那一条记录都加进去了,当然找到那条记录了,日期也就找到了
            tempList.append(allItemList[i])

    allDateList.append(tempList)

print("符合条件的条目如下:")
for item in allDateList:
    print(item)
    print()

 

你可能感兴趣的:(Python关于csv读写的小题目笔记)