[英]python: creating nested Lists within for loops
我想處理 csv 文件,我想要的輸出是每列不同值的數量(這應該在unique_list
中)和列中的數據類型(在'types_list'中)到目前為止我有一個嵌套循環:
對於unique_list
:返回一個包含所有唯一值的列表,我試圖通過創建另一個列表來解決這個問題,該列表在每次迭代中填充了相應的唯一列項目作為另一個列表,這樣我可以在另一個步驟中計算每個列表中的項目一個列表,但到目前為止我還沒有實現
對於types_list
:在這里我想實現幾乎相同的事情,一個列表列表,其中每個“子列表”包含一列的數據類型 - 我嘗試了這個,可以在代碼中看到,但我得到的結果是一個列表列表,其中子列表確實包含一列的數據類型,但這會重復多次而不是一次。 在下一步中,我想遍歷每個列表以檢查子列表中的數據類型是否都相同,如果是,則 append 將相應類型添加到列表中(如果它們不同,則 append 'object'到這個列表)。
我知道使用 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]
從文件讀取應該在'with'語句中,如果不是,文件已經關閉,從它讀取會引發異常。
with open(filePath, 'r') as f:
reader = csv.reader(f)
l = list(reader)
對於 type_list:您使用字符串 'int' 來表示一個 int,但使用類型 class 'str' 來表示一個字符串。 我認為您應該始終使用其中一種,即使用 class int 類型來表示 int object。
在嵌套循環中,您 append 您的工作列表在列項目上的每次迭代中,您不應該只在完成對列的循環后才這樣做嗎? 那是在嵌套循環完成之后。
for x in range(0, columns):
looping_list = [item[x] for item in without_header]
worklist = []
for b in looping_list:
try:
int(b)
worklist.append(int)
except:
worklist.append(type(b))
types_list.append(worklist)
要將每個子列表合並為 1 個值,我們可以將子列表轉換為 Set。 Set 刪除重復項,因此如果它的長度為 1,我們知道子列表僅包含 1 個唯一項。
# uniting the sublist into 1 value
new_types_list = []
for sub_list in types_list:
if len(set(sub_list)) == 1:
# if all items in the sublist are the same
# use the first value in the list
new_types_list.append(sub_list[0])
else:
# they are not all the same
new_types_list.append(object)
對於 unique_list:您正在嘗試使用在循環中創建的變量,您在其中迭代列,因此它僅包含最后一列中的項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.