【发布时间】:2015-09-11 21:36:48
【问题描述】:
我有一个程序可以读取 .csv 文件,检查列长度是否不匹配(通过将其与标题字段进行比较),然后将找到的所有内容作为列表返回(然后将其写入文件)。我想用这个列表做的,是列出结果如下:
发现相同不匹配的行号:该行中的列数
例如
rows: n-m : y
其中 n 和 m 是共享相同数量的与标题不匹配的列的行数。
我研究了这些主题,虽然这些信息很有用,但它们并没有回答问题:
Find and list duplicates in a list?
Identify duplicate values in a list in Python
这就是我现在的位置:
r = csv.reader(data, delimiter= '\t')
columns = []
for row in r:
# adds column length to a list
colm = len(row)
columns.append(colm)
b = len(columns)
for a in range(b):
# checks if the current member matches the header length of columns
if columns[a] != columns[0]:
# if it doesnt, write the row and the amount of columns in that row to a file
file.write("row " + str(a + 1) + ": " + str(columns[a]) + " \n")
文件输出如下所示:
row 7220: 0
row 7221: 0
row 7222: 0
row 7223: 0
row 7224: 0
row 7225: 1
row 7226: 1
当期望的最终结果是
rows 7220 - 7224 : 0
rows 7225 - 7226 : 1
所以我本质上需要的是一个字典,其中键是具有重复值的行,值是所述不匹配中的列数。我基本上认为我需要的东西(在一个可怕的书面伪代码中,现在我在写这个问题多年后阅读它没有任何意义),就在这里:
def pseudoList():
i = 1
ListOfLists = []
while (i < len(originalList)):
duplicateList = []
if originalList[i] == originalList[i-1]:
duplicateList.append(originalList[i])
i += 1
ListOfLists.append(duplicateList)
def PseudocreateDict(ListOfLists):
pseudoDict = {}
for x in ListOfLists:
a = ListOfLists[x][0] #this is the first node in the uniqueList created
i = len(ListOfLists) - 1
b = listOfLists[x][i] #this is the last node of the uniqueList created
pseudodict.update('key' : '{} - {}'.format(a,b))
然而,这似乎是做我想做的事情非常复杂的方式,所以我想知道是否有 a) 更有效的方式 b) 更简单的方式来做到这一点?
【问题讨论】:
标签: python list csv dictionary duplicates