如何在python中不带括号的情况下写入文件 [英] How to write to file without parenthesis in python
问题描述
当我写文件结果时:
output=knew[i][0],knew[i][1], knew[i][2],eigenval[k],group[i]
value=str(output)
o.write(value+'\n')
我得到:
(0.05, 0.05, 0.166667, -0.8513056, 0.9881956035137526)
(0.05, 1.05, 0.166667, -0.8513056, 0.011652226336523394)
(0.05, -0.9500000000000002, 0.166667, -0.8513056, 0.00015217014972403685)
如何写文件而不加括号?
How to write to file so it doesn't add brackets?
推荐答案
代替
value = str(output)
你可以做
value = ', '.join(map(str, output))
您看到的是元组的字符串表示形式.在那里是因为您在其中调用了str
.
What you see is the string representation of a tuple. It's there because you called str
on it.
str.join
方法的作用是将可迭代对象(例如元组或列表),将调用它的字符串用作定界符(此处', '
是定界符,map(str, output)
是字符串的可迭代变量.)成单个字符串. map
将函数应用于可迭代对象的每个元素.在这种情况下,str
应用于output
的每个元素,因此我们可以迭代字符串,而不是浮点数.
What the str.join
method does is join an iterable (e.g. a tuple or a list) of strings, using the string that it's called on as a delimiter (here ', '
is the delimiter and map(str, output)
is the iterable of strings.) into a single string. map
applies a function to each element of an iterable. In this case, str
is applied to each element of output
, so that we have an iterable of strings, rather than float numbers.
或者(有点怪异),您可以从具有的值中去除括号:
Alternatively (a bit hacky) you can just strip off the parentheses from the value that you have:
value = str(output)[1:-1]
这篇关于如何在python中不带括号的情况下写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!