我该如何制作一大串花车?

时间:2014-08-03 20:46:03

标签: python concatenation

我正在创建一个包含大量数字数据的arff文件。现在,由于我的特征向量非常大,我最终得到了像这样的代码

with(file,'w') as myfile:
    s = number + ","
    s += number + ","
    s += number + ","
    s += number + ","
    ...
    myfile.write(s)

由于我对Python很陌生,我显然忘记了Python似乎不允许将浮点数连接到类似的字符串并给出以下错误。

unsupported operand type(s) for +: 'numpy.float64' and 'str'

那么一个更有经验的python程序员如何处理这个问题,或者我真的必须将所有这些数字转换成这样的字符串

with(file,'w') as myfile:
    s = str(number) + ","
    s += str(number) + ","
    s += str(number) + ","
    s += str(number) + ","
    ...
    myfile.write(s)

1 个答案:

答案 0 :(得分:7)

不要手动写CSV行。使用csv module

with(file, 'wb') as myfile:
    writer = csv.writer(myfile)
    writer.writerow([number1, number2, number3])

列表中的每个元素都会转换为您的字符串。

使用numpy数组时,您可以使用numpy.savetext()来获得相同的结果。

即使没有csv模块,您只需将一系列值与str.join()合并为一个字符串,并明智地帮助map()确保所有值都是字符串:

s = ','.join(map(str, [number1, number2, number3]))

后者的快速演示(使用Python 2):

>>> number = 42.4245
>>> string = 'The quick brown fox'
>>> empty = None
>>> map(str, [number, string, empty])
['42.4245', 'The quick brown fox', 'None']
>>> ','.join(map(str, [number, string, empty]))
'42.4245,The quick brown fox,None'