你好,我為生物學家上了一門 Python 課程,并且有關于使用 csv 檔案的知識,我陷入了最后一個問題,即從 csv 檔案中創建字典,鍵為 (c, b) 的元組,值是串列所有(first、finish、fix/ext)值的元組,它們具有相同的 c、b 值。csv 看起來像這樣:
N,c,g,b,first,finish,fix/ext
1000,1.0,0.02,3.0,602,1661,0
1000,0.8,0.02,3.0,42,911,0
1000,1.0,0.02,3.0,945,2164,0
1000,1.0,0.02,3.0,141,954,0
結果需要如下所示:
: {(1, 3) : [(602, 1661, 0), (945, 2164, 1), (687, 716, 1)], (1, 1.5) : [(35, 287, 0), (803, 1402, 0), …], …}
現在我設法做到了:
def read_results(full_file_path):
csv_dict = {}
with open(full_file_path,'r') as t:
table = t.readlines()[1:]
for line in table:
line = line.replace('\n', '')
line = line.split(',')
csv_dict[line[0]] = line[1:]
print(csv_dict)
這給了我這個:
{'1000': ['1.0', '0.02', '3.0', '602', '1661', '0']}
但似乎無法理解如何使用我需要的鍵以及如何將所有相應值的串列放入元組中
哦,我不能使用 import csv 或其他匯入
uj5u.com熱心網友回復:
你幾乎完成了,唯一剩下的就是設定,什么是你的鑰匙,你的價值觀是什么。在這里,我撰寫了一個最終確定它的代碼:
def read_results(full_file_path):
csv_dict = {}
with open(full_file_path,'r') as t:
table = t.readlines()[1:]
for line in table:
line = line.replace('\n', '')
line = line.split(',')
line = list(map(float, line)) # optional, if you want to have numbers as floats and not strings
'''
line[1] - c
line[3] - b
KEY: (c,b) - tuple of c and b
TUPLE OF CORRESPONDING VALUES: (line[4], line[5], line[6]) - tuple of first, finish, fix/ext
'''
key = (line[1],line[3])
if key in csv_dict:
# append a new value if key is already in the dict
csv_dict[key].append((line[4], line[5], line[6]))
else:
# create a new value by the key if it is not in the dict
csv_dict[key] = [(line[4], line[5], line[6])]
return csv_dict
dict = read_results("file.csv")
print(dict)
# try to get the values of dict by some value:
key = (1.0, 3.0) #key = ("0.8", "3.0") if strings were not converted to floats
print(dict[key])
我希望我通過相應的評論使其可以理解。如果您有更多問題 - 寫下來,我會盡力回答。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/445734.html
