可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm writing a python function to append data to text file, as shown in the following,
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')
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.
回答1:
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
EDIT: 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'
回答2:
If you don't know what is the type of var you can check type using
from collections import Iterable if isinstance(var,Iteratable): mystring=''.join(map(str,var)) else: mystring=str(var)
回答3:
Maybe what you're looking for is repr()
It's the opposite of the eval function.
Here's what eval does:
eval('[1,3]') # [1, 3]
Here's what repr does:
repr('example') # "'example'" repr(0.1) # '0.1' repr([1,2]) # '[1,2]'
回答4:
str is able to convert any type into string. It can be numpy.array / list / float
# using numpy array new_array = numpy.array([1,2,3]) str(new_array) >> '[1 2 3]' # using list new_list = [1, 2, 3] str(new_list) >> '[1, 2, 3]' # using float new_float = 1.1 str(new_float) >> '1.1'