【发布时间】:2014-12-11 22:23:03
【问题描述】:
我正在尝试读取 CSV 文件并将数据作为整数列表返回。 CSV 文件为 6 列宽和 2 行。使用 Python 3.4。
它总是以 strs 列表的形式出现。搜索 StackOverflow 和 Google 显示了 7 种不同的方法来做到这一点,但都不起作用。这些显示在我尝试过的代码下方。
import csv
b = []
with open('C:\Python34\DataforProgramstorun\\csv data6x2.csv') as f:
reader = csv.reader(f)
for row in reader :
b.append(row) # this gives me a list of list each element a csv str from print (b)
print (b)
结果是:
[['2', '5', '15', '17', '19', '20'], ['6', '8', '14', '18', '21', '30']]
我希望它是:
[[2, 5, 15, 17, 19, 20], [6, 8, 14, 18, 21, 30]]
以下都不起作用:
[ int(x) for y in b for x in y.split() ] #builtins.AttributeError: 'list' object has no attribute 'split'[int(x) for x in ' '.join(b).split ()] #builtins.TypeError: sequence item 0: expected str instance, list foundimport itertools as it; new =list(it.imap(int,b)) #builtins.AttributeError: 'module' object has no attribute 'imap'for i in range (0,len(b)): b[i] = int (b[i]) #builtins.TypeError: int() argument must be a string or a number, not 'list'results = b; results = [int(i) for i in results] ##builtins.TypeError: int() argument must be a string or a number, not'list'b = list(map(int,b)) #builtins.TypeError: int() argument must be a string or a number, not 'list'[int(i) for i in b] #builtins.TypeError: int() argument must be a string or a number, not 'list'
【问题讨论】:
-
在 #3 上,Python 3 没有
itertools.imap,因为map现在是一个迭代器。在其他大多数情况下,请注意您需要将它们应用到b中的每个列表,而不是b本身。
标签: string list csv python-3.x