我有以下代码
$ipython
> import csv
> with open('q1_4.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter = ' ', quotechar = '|')
for row in reader:
print [tuple(row)]
在每一行中,我有四个值,每个值都是一个字符串,一个数字,一个数字和一个数字。我怎样才能打印出每行的“string”,num,num,num,而不是“string”,“string”,“string”,“string”?
已更新 我根据以下评论进行了此修改:
import csv
from itertools import chain
result = []
with open("q1_4.csv", "rb") as csvfile:
reader = csv.reader(csvfile, delimiter = ",", quotechar = "|")
for row in reader:
result.append(tuple(chain([row[0]], map(float, row[1:4]))))
print result
由于我对将元组结果放入列表感兴趣,我有结果= []和以下修改。但是,这给了我与我的数据集中的行数一样多的重复。怎么可以改善?谢谢!!
答案 0 :(得分:0)
如果您只关注格式化
with open('q1_4.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter = ' ', quotechar = '|')
for row in reader:
print '"{}", {}, {}, {}'.format(*row)
测试:
>>> row = ["string", "1", "2", "3"]
>>> print '"{}", {}, {}, {}'.format(*row)
"string", 1, 2, 3
在评论中根据您的请求更新。以下是可用于返回元组的几个选项
return (row[0],) + tuple(int(n) for n in row[1:]) # Python 2 and 3
return (row[0],) + tuple(map(int, row[1:])) # Python 2 and 3
return tuple(chain([row[0]], map(int, row[1:]))) # Python 2 and 3; requires importing `chain` from `itertools`
虽然我更喜欢Python 3:
return (row[0], *map(int, row[1:])) # Python 3 only
如果你想返回一个元组列表,可以采用任何一种结构(为了简洁,我会选择第三个)并执行:
return [(row[0], *map(int, row[1:])) for row in reader]
注意您只能从函数返回,因此您必须将其全部包装到函数中。