【发布时间】:2015-10-01 01:58:03
【问题描述】:
假设我在下面有一个“players.csv”文件,其中包含一些 NFL 球员的数据。我的目标是读取文件,并创建一个字典,其中键作为玩家的身高,值作为玩家资料列表。 (在元组中)
HEIGHT,NAME,DRAFTED,AGE,POSITION,WEIGHT
6,Aaron,2005,31,QB,225
5,Jordy,2008,30,WR,217
5,Randall,2011,24,WR,192
玩家资料元组示例,'name' 必须是字符串,'age' 和 'position' 必须是整数。起草的“年份”和“职位”必须忽略。
player_profile = (name, age, position)
预期的字典:
# players height are keys, player profiles are values.
dict = {
6: [('Aaron', 31, 225)]
5: [('Jordy', 30, 217), ('Randall', 24, 192)]
}
以下是我到目前为止的内容,但我被卡住了。
final_dict = {}
#open csv file
with open(filename) as f:
info = f.read()
#split the newline characters
info2 = info.split()
#exclude the header
info3 = info2[1:]
【问题讨论】:
-
查看文档中的 csv.reader,它使这变得非常简单。
标签: python list csv dictionary tuples