将浮动列表连接到Python中以空格分隔的字符串中 [英] Join float list into space-separated string in Python
本文介绍了将浮动列表连接到Python中以空格分隔的字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在python中有一个浮点列表:
I have a list of floats in python:
a = [1.2, 2.9, 7.4]
我想加入它们以产生一个用空格分隔的字符串-即:
I want to join them to produce a space-separated string - ie.:
1.2 2.9 7.4
但是,当我尝试时:
print " ".join(a)
由于它们是浮动的,并且在我尝试时出现错误:
I get an error because they're floats, and when I try:
print " ".join(str(a))
我知道
[ 1 . 2 , 1 . 8 , 5 . 2 9 9 9 9 9 9 9 9 9 9 9 9 9 9 8 ]
我如何连接所有元素,同时将元素(分别)转换为字符串,而不必遍历所有元素?
How can I join all of the elements, while converting the elements (individually) to strings, without having to loop through them all?
推荐答案
您需要将列表的每个条目转换为字符串,而不是一次转换整个列表:
You need to convert each entry of the list to a string, not the whole list at once:
print " ".join(map(str, a))
如果您想更多地控制转换为字符串(例如,控制要打印的位数),可以使用
If you want more control over the conversion to string (e.g. control how many digits to print), you can use
print "".join(format(x, "10.3f") for x in a)
请参见格式说明符的语法文档.
这篇关于将浮动列表连接到Python中以空格分隔的字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文