2 回答

TA貢獻1790條經(jīng)驗 獲得超9個贊
嘗試pandas:
import pandas as pd
df = pd.read_csv('your_file.csv', header=None)
(df.ffill() # fill the blank with the previous Name
.groupby([0])[1] # collect those with same name
.apply(list) # put those in a list
.to_dict() # make a dictionary
)
輸出:
{'Name1': ['Value1', 'Value2', 'Value3'],
'Name2': ['Value40', 'Value50', 'Value60'],
'Name3': ['Value5', 'Value10', 'Value15']}
更新:純 python(3) 解決方案:
with open('your_file.csv') as f:
lines = f.readlines()
d = {}
for line in lines:
row = line.split(',')
if row[0] != '':
key = row[0]
d[key] = []
d[key].append(row[1])
d

TA貢獻1810條經(jīng)驗 獲得超5個贊
我認為您面臨的問題是由于您的嵌套循環(huán)。兩個循環(huán)都指向同一個迭代器。您將在找到 Name1 后開始第二個循環(huán),并在找到 Name2 時將其中斷。到外部循環(huán)在中斷后繼續(xù)時,您已經(jīng)跳過了 Name2。
您可以在同一個循環(huán)中同時擁有這兩個條件:
# with open("GroupsCSV.csv") as csv_file:
# reader = csv.reader(csv_file)
reader = [[1,2,3],[None,5,6]] # Mocking the csv input
objlist = []
for row in reader:
if row[0] and row[2]:
objlist.clear()
objlist.append(row[2])
elif not row[0] and row[2]:
objlist.append(row[2])
print(objlist)
編輯:我更新了代碼以提供可測試的輸出。打印輸出如下所示:
[3]
[3, 6]
添加回答
舉報