Python“.write”
我怎样才能“转换”这个:
input=[(0.25 , 'x1'),(0.20 , 'x2'), ............................]
这样我就可以在 test.txt 中只写这个: x1=0.25,x2=0.20,x3=......................
f = open('test.txt', 'w')
f.write(输入)
f.close()
我知道打印,这个工作正常:
print ' '.join("%s=%s" % (y, x) for x,y in input)
但我不能“导入”到f.write(...)
编辑:感谢大家,一切顺利,我不记得我可以使用:
f.write(' '.join("%s=%s" % (y, x) for x,y in input))
How can I "convert" this:
input=[(0.25 , 'x1'),(0.20 , 'x2'), ............................]
so that I can write in test.txt only this:
x1=0.25, x2=0.20, x3= ..................
f = open('test.txt', 'w')
f.write(input)
f.close()
I know for print, this work ok:
print ' '.join("%s=%s" % (y, x) for x,y in input)
but I can't "import" into f.write(...)
Edit: Thanks to all, all worked, I didn't remember that I can use:
f.write(' '.join("%s=%s" % (y, x) for x,y in input))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有什么问题吗
?
或者
有一个细微的区别,前者不会有尾随换行符。不过很容易修复。
Anything wrong with
?
Or
There's a minor difference in that the former won't have a trailing newline character. Easily fixed though.
您有
' '.join("%s=%s" % (y, x) for x,y in input)
并且您正在打印它;将其传递给f.write
,这是一个完全有效的表达式:You have
' '.join("%s=%s" % (y, x) for x,y in input)
and you are printing that; pass that tof.write
, it's a perfectly valid expression:试试这个:
Try this:
如果您想使用
print
,正确的方法取决于您使用的 Python 版本。对于 Python 2:对于 Python 3:
If you would like to use
print
, the correct method depends on which version of Python you are using. For Python 2:For Python 3:
input
,因为这是一个内置函数。print
语句替换为f.write(' '.join("% s=%s" % (y, x) for x, y in myList)
它应该工作得很好input
since that is a built-in functionprint
statement withf.write(' '.join("%s=%s" % (y, x) for x, y in myList)
and it should work just fine