我正在读取csv文件中的数据,其中一些值是"无"。然后,正在读入的值包含在列表中。
列表传递给一个函数,该函数要求列表中的所有值都是int()格式。
但是,我不能将其应用于"无"字符串值存在。我试过更换"无"使用无,或使用""但这没有奏效,导致错误。列表中的数据也需要保持在同一位置,所以我不能完全忽略它们。
我可以替换所有"无" 0但是没有!= 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")
会有很多低效率或奇怪的做事方式,试图慢慢学习。
将所有Nones设置为0,这并不能真正反映Chrome在特定日期之前的存在。感谢
答案 0 :(得分:0)
如果没有看到您的代码,我只能提供有限的帮助。
听起来你需要使用ast.literal_eval()。
import ast
csvread = csv.reader(file)
list = []
for row in csvread:
list.append(ast.literal_eval(row[0]))