2017-09-03 91 views
1

这是我之前创建的代码。如何将csv列表转换为int?

import sys,csv 
from matplotlib import pyplot 
from time import sleep 
import numpy as ma 
import pandas 
import serial 
file = open("C:/Users/rickchen/Desktop/MQTT1/testfile.csv") 
book = csv.reader(file) 
b=list(book) 
print b 
print type(b) 

我发现,结果就是这样

[['114', '119', '116', '118', '120', '118', '113', '118', '121', '122', '117', '114', '112', '114', '115', '120', '128', '128', '120', '112', '110', '117', '122', '118', '112', '113', '122', '120', '116', '114', '118', '117', '128', '132', '130', '112']] 
<type 'list'> 

它的字符串,并且不能被用来绘制。

所以,我想出一个新的代码来解决这个问题

import sys,csv 
from matplotlib import pyplot 
from time import sleep 
import numpy as ma 
import pandas 
import serial 
file = open("C:/Users/rickchen/Desktop/MQTT1/testfile.csv") 
book = csv.reader(file) 
b=list(book) 
c=[] 
for bx in b: 
    c.append(int(bx)) 
print c 
print type(c) 

,但它显示类型错误:int()函数的参数必须是字符串或数字,而不是“名单”

所以,我想知道如何解决这个问题。主人可以给我一些建议吗?非常感谢!!

+0

'b = [int(e)for e in b]' – martijnn2008

+0

'book = [int(line.strip())for line in csv.reader(file)]'应该直接工作。 – FabienP

+0

是不是'.strip()'毫无意义? – martijnn2008

回答

0

你的列表结果中包含另一个列表,你需要遍历他们两个:

c = [int(val) for list1 in b for val in list1] 

你的代码可以被转换成这样:

with open("C:/Users/rickchen/Desktop/MQTT1/testfile.csv") as file: 
    book = csv.reader(file) 
    c = [int(val) for list1 in book for val in list1] 

print(c) 

(使用with作为上下文管理避免关闭文件末尾)

+0

它的工作原理!非常感谢你^ _^ –

+0

@陈俊良我不知道你想如何绘制下一个,你不需要从你的csv逐行获得结果? – PRMoureu

0

正如我们可以在您的输出中注意到的,b是列表的列表。因此,当bx也将是一个列表,而不是int。因此,您必须只取b列表中的第一个元素,并且我们的代码修改如下:

import sys,csv 
from matplotlib import pyplot 
from time import sleep 
import numpy as ma 
import pandas 
import serial 
file = open("C:/Users/rickchen/Desktop/MQTT1/testfile.csv") 
book = csv.reader(file) 
b=list(book) 
c=[] 
for bx in b[0]: 
    c.append(int(bx)) 
print c 
print type(c)`