如何从打印[1,2,3]打印到文本文件中的Python 1,2,3 Python
问题描述:
我正在使用以下循环遍历numpy数组并打印到单独的文本文件中。如何从打印[1,2,3]打印到文本文件中的Python 1,2,3 Python
c= np.array([1, 2, 3])
nc = c.astype(np.int)
for x in nc:
print >> thing_here, x
但当我打开thing_here文本文件,其打印我的数组为[1, 2, 3]
,而不是1, 2, 3
我怎样才能摆脱[]的吗?
答
的join
命令将做到这一点:
c = np.array([1,2,3])
c_joined = ' '.join(map(str,c))
如果数组已经是一个字符串列表,你可以忽略map()
命令,只需使用:
c = np.array([1,2,3])
c_joined = ' '.join(c)
然后做打印到使用此连接字符串的文件命令。作为进一步的说明,np.savetxt()
是一个有用的命令
'print >> thing_here,repr(x)[1:-1]'。 –
'','.join(map(str,x))',但可能是直接使用'csv.writer'更好吗? – myaut
@ChristianDean导致它打印为rray([1,2,3]) – cryptofish