2017-09-03 137 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)`