我正在尝试读取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 found
import 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'
答案 0 :(得分:2)
>>> lst = [['2', '5', '15', '17', '19', '20'], ['6', '8', '14', '18', '21', '30']]
>>> [[int(x) for x in inner] for inner in lst]
[[2, 5, 15, 17, 19, 20], [6, 8, 14, 18, 21, 30]]
您尝试过的所有解决方案的问题在于您只能深入一级。所以你确实考虑了外部列表,但是然后尝试直接使用内部列表,这通常会失败。要解决此问题,您需要直接处理内部列表。你也可以这样解决:
for i, sublist in enumerate(b):
b[i] = [int(x) for x in sublist]
而不是[int(x) for x in sublist]
您还可以使用众多其他解决方案之一将(子)列表中的所有字符串转换为整数,例如list(map(int, sublist))
。