【发布时间】:2021-04-08 04:52:44
【问题描述】:
我想处理一个 csv 文件,我想要的输出是每列不同值的数量(这应该在 unique_list 中)和列中的数据类型(在 'types_list' 中)
到目前为止,我有一个嵌套循环:
-
对于
unique_list:返回一个包含所有唯一值的列表,我试图通过创建另一个列表来解决这个问题,该列表在每次迭代中填充了相应的唯一列项作为另一个列表,以便我可以在另一个步骤中计数列表中每个列表的项目,但到目前为止我还没有实现 -
对于
types_list:在这里我想实现几乎相同的事情,一个列表列表,其中每个“子列表”包含一列的数据类型 - 我尝试了这个,可以在代码中看到,但我结果是一个列表列表,其中子列表确实包含一列的数据类型,但这会重复多次而不是一次。 在这里的下一步中,我想遍历每个列表以检查子列表中的数据类型是否都相同,如果是,则将相应的类型附加到列表中(如果它们不同,则附加“对象”到这个列表)。
我知道使用 pandas 等可能会更容易,但我想为此使用纯 python
with open(filePath,'r') as f:
reader = csv.reader(f)
l=list(reader)
rows = len(l)-1 #counts how many rows there are in the CSV, -1 to exclude the header
columns = len(l[0]) #the number of columns is given by the number of objects in the header list, at least in a clean CSV
without_header = l[1:] #returns the csv list without the header
unique_list = []
types_list = []
looping_list = []
for x in range(0,columns):
looping_list = [item[x] for item in without_header]
worklist = []
for b in looping_list:
try: #here i'm trying if the value in the CSV file could be an integer just in case it isn't recognised as one
int(b)
worklist.append('int')
types_list.append(worklist)
except:
worklist.append(type(b))
types_list.append(worklist)
for n in looping_list:
if n not in unique_list:
unique_list.append(n)
例如,对于这个 CSV:
Position,Experience in Years,Salary
Middle Management,5,5000
Lower Management,2,3000
Upper Management,1,7000
Middle Management,5,5000
Middle Management,7,7000
Upper Management,10,12000
Lower Management,2,2000
Middle Management,5,500
Upper Management,7, NoAnswer
我希望 unique_list 返回 [3,5,7] 和 types_list 返回 [str,int,object]
【问题讨论】:
标签: python list iteration nested-lists