【发布时间】:2016-03-07 09:27:38
【问题描述】:
我正在从一个 csv 文件中读取数据,其中一些值为“无”。正在读入的值随后包含在一个列表中。
列表被传递给一个函数,该函数要求列表中的所有值都是 int() 格式。
但是我不能在存在“无”字符串值的情况下应用它。我试过用 None 或用 "" 替换 "None" 但没有奏效,它会导致错误。列表中的数据也需要保持在同一个位置,所以我不能完全忽略它们。
我可以用 0 替换所有“无”,但 None != 0 真的。
编辑:我已经添加了我的代码,希望它会更有意义。尝试从 csv 文件中的数据创建折线图:
import csv
import sys
from collections import Counter
import pygal
from pygal.style import LightSolarizedStyle
from operator import itemgetter
#Read in file to data variable and set header variable
filename = sys.argv[1]
data = []
with open(filename) as f:
reader = csv.reader(f)
header = reader.next()
data = [row for row in reader]
#count rows in spreadsheet (minus header)
row_count = (sum(1 for row in data))-1
#extract headers which I want to use
headerlist = []
for x in header[1:]:
headerlist.append(x)
#initialise line chart in module pygal. set style, title, and x axis labels using headerlist variable
line_chart = pygal.Line(style = LightSolarizedStyle)
line_chart.title = 'Browser usage evolution (in %)'
line_chart.x_labels = map(str, headerlist)
#create lists for data from spreadsheet to be put in to
empty1 = []
empty2 = []
#select which data i want from spreadsheet
for dataline in data:
empty1.append(dataline[0])
empty2.append(dataline[1:-1])
#DO SOMETHING TO "NONE" VALUES IN EMPTY TWO SO THEY CAN BE PASSED TO INT CONVERTER ASSIGNED TO EMPTY 3
#convert all items in the lists, that are in the list of empty two to int
empty3 = [[int(x) for x in sublist] for sublist in empty2]
#add data to chart line by line
count = -1
for dataline in data:
while count < row_count:
count += 1
line_chart.add(empty1[count], [x for x in empty3[count]])
#function that only takes int data
line_chart.render_to_file("browser.svg")
会有很多低效或怪异的做事方式,尝试慢慢学习。
所有的 None 都设置为 0,但这并不能真正反映 Chrome 在某个日期之前的存在。谢谢
【问题讨论】:
-
请阅读this
标签: python string csv nonetype