How to split a CSV row so row[0] is the name and any remaining items are a tuple?

不羁岁月 提交于 2019-12-10 20:59:06

问题


I have a csv file in which the first column is the name of a baseball player, and then each subsequent item in the file is a statistic. I'd like to be able to import the file so that the player name was equal to a tuple of the statistics.

Right now when I import the file using this code:

Orioles = file("Orioles.csv", "rU")
for row in Orioles:
    print row

I get something like this:

[Nick_Markakis, '.005', '.189', '.070', '.002', '.090']
[Adam_Jones, '.005', '.189', '.070', '.002', '.090']

I'd like to have the statistics be listed as floats rather than strings and be able to pull out the player name, and use it later, like this:

Nick_Markakis = ['.005', '.189', '.070', '.002', '.090']
Adam_Jones = ['.005', '.189', '.070', '.002', '.090']

回答1:


Having the player name be it's own variable is not as helpful as you might think: you can't iterate over the collection (because there isn't one), your code is fixed and fragile (you have to add/remove lines when a player name is added or removed from your file, etc.

If, however, you have them in a dictionary -- well, now you can iterate, and you can still ask for players by name.

player_data = file("Orioles.csv", "rU")
orioles = dict()
for row in player_data:
    row = row.split(',')
    orioles[row[0]] = tuple(map(float, row[1:]))

print orioles.keys()
# ['Adam_Jones', 'Nick_Markakis']
print orioles['Adam_Jones']
# (0.005, 0.189, 0.07, 0.002, 0.09)

Rather than the row.split(',') trick above, you'll probably want to use the csv module in real code.




回答2:


Orioles = file("Orioles.csv", "rU")
stats = dict((row[0], map(float, row[1:])) for row in Orioles)
# In Python 2.7+: stats = {row[0]: map(float, row[1:]) for row in Orioles}

Now, you can access the stats like this:

print(sum(stats['Nick_Markakis'])) # 0.356


来源:https://stackoverflow.com/questions/7394644/how-to-split-a-csv-row-so-row0-is-the-name-and-any-remaining-items-are-a-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!