在python中将numpy,list或float转换为字符串 [英] Convert numpy, list or float to string in python

查看:563
本文介绍了在python中将numpy,list或float转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python函数,将数据追加到文本文件中,如下所示,

I'm writing a python function to append data to text file, as shown in the following,

问题是变量var可能是一维numpy数组,一维列表或只是浮点数,我知道如何将numpy.array/list/float分别转换为字符串(意思是给定的类型),但是有一种方法可以将var转换为字符串而不知道其类型吗?

The problem is the variable, var, could be a 1D numpy array, a 1D list, or just a float number, I know how to convert numpy.array/list/float to string separately (meaning given the type), but is there a method to convert var to string without knowing its type?

def append_txt(filename, var):
    my_str = _____    # convert var to string
    with open(filename,'a') as f:
        f.write(my_str + '\n')

感谢您的评论,对不起,也许我的问题还不够清楚. numpy上的str(var)会给出类似[]的内容.例如,var = np.ones((1,3)), str(var)将给出[[1. 1. 1.]],而[]是不需要的,

Edit 1: Thanks for the comments, sorry maybe my question was not clear enough. str(var) on numpy would give something like []. For example, var = np.ones((1,3)), str(var) will give [[1. 1. 1.]], and [] is unwanted,

由于我要写干净的数字(表示没有[]),所以类型检查似乎是不可避免的.

Edit 2: Since I want to write clean numbers (meaning no [ or ]), it seems type checking is inevitable.

推荐答案

类型检查不是执行所需操作的唯一选择,但绝对是最简单的方法之一:

Type checking is not the only option to do what you want, but definitely one of the easiest:

import numpy as np

def to_str(var):
    if type(var) is list:
        return str(var)[1:-1] # list
    if type(var) is np.ndarray:
        try:
            return str(list(var[0]))[1:-1] # numpy 1D array
        except TypeError:
            return str(list(var))[1:-1] # numpy sequence
    return str(var) # everything else

另一种简单的方法,不使用类型检查(感谢jtaylor给我这个想法),是将所有内容都转换为相同的类型(np.array),然后将其转换为字符串:

Another easy way, which does not use type checking (thanks to jtaylor for giving me that idea), is to convert everything into the same type (np.array) and then convert it to a string:

import numpy as np

def to_str(var):
    return str(list(np.reshape(np.asarray(var), (1, np.size(var)))[0]))[1:-1]

示例用法(两种方法均得出相同的结果):

Example use (both methods give same results):

>>> to_str(1.) #float
'1.0'
>>> to_str([1., 1., 1.]) #list
'1.0, 1.0, 1.0'
>>> to_str(np.ones((1,3))) #np.array
'1.0, 1.0, 1.0'

这篇关于在python中将numpy,list或float转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆