我的目标是从csv file
中读取信息并将其保存到字典中(感谢注释)。字典将包含名称作为key
,数字作为value
。字典应是动态的,即应适用于n个行字符。所需:能够更改键值,只创建一个字典,而不是多个字典
name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5
Alice = [2,8,3]
Bob = [4,1,5]
etc.
代码也应该使用相同的逻辑来实现这一点:
name,AGATC,TTTTTTCT,AATG,TCTAG,GATA,TATC,GAAA,TCTG
Albus,15,49,38,5,14,44,14,12
Cedric,31,21,41,28,30,9,36,44
Draco,9,13,8,26,15,25,41,39
Fred,37,40,10,6,5,10,28,8
Ginny,37,47,10,23,5,48,28,23
Hagrid,25,38,45,49,39,18,42,30
Harry,46,49,48,29,15,5,28,40
Hermione,43,31,18,25,26,47,31,36
James,46,41,38,29,15,5,48,22
Kingsley,7,11,18,33,39,31,23,14
Lavender,22,33,43,12,26,18,47,41
Lily,42,47,48,18,35,46,48,50
Lucius,9,13,33,26,45,11,36,39
Luna,18,23,35,13,11,19,14,24
Minerva,17,49,18,7,6,18,17,30
Neville,14,44,28,27,19,7,25,20
Petunia,29,29,40,31,45,20,40,35
Remus,6,18,5,42,39,28,44,22
Ron,37,47,13,25,17,6,13,35
Severus,29,27,32,41,6,27,8,34
Sirius,31,11,28,26,35,19,33,6
Vernon,26,45,34,50,44,30,32,28
Zacharias,29,50,18,23,38,24,22,9
以下是我的尝试:
def readcsv(n):
with open(f'{n}','r') as f:
readed = csv.reader(f)
for row in readed:
key = row[0]
value = row[1:]
#print(f"{key} and {value}")
dic = dict(key = value)
print(dic)
OUTPUT :
{'key': ['AGATC', 'AATG', 'TATC']}
{'key': ['2', '8', '3']}
{'key': ['4', '1', '5']}
{'key': ['3', '2', '5']}
你说的“name”是指变量名吗?我想这样做是可能的
然而,在运行时设置变量名是非常不传统的。命名空间的更好解决方案是使用字典:
您可以使用
rows["name of row"]
访问相关元素您可以使用
pandas
库轻松地读入.csv
文件。你要找的最好是一本字典,字典里的名字是键,列表是值如果您有一个字典,并且想要更改某个键的值(例如,下面的
dict
,d
中的Albus
),这是非常简单的代码
输出:
虚拟数据
相关问题 更多 >
编程相关推荐