[英]Join float list into space-separated string in Python
I have a list of floats in python:我在 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
However, when I try:但是,当我尝试:
print " ".join(a)
I get an error because they're floats, and when I try:我收到一个错误,因为它们是浮动的,当我尝试时:
print " ".join(str(a))
I get我明白了
[ 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 (eg control how many digits to print), you can use如果您想更好地控制转换为字符串(例如控制要打印的位数),您可以使用
print "".join(format(x, "10.3f") for x in a)
See the documentation of the syntax of format specifiers .请参阅格式说明符语法的文档。
Actually you have to loop through them.实际上,您必须遍历它们。 With a generator or list comprehension that looks pretty clean:使用看起来很干净的生成器或列表推导:
print " ".join(str(i) for i in a)
(map loops through them, as does the format code) (地图循环通过它们,格式代码也是如此)
The generator has the advantage over the list comprehension of not generating a second intermediate list, thus preserving memory.生成器的优势在于不生成第二个中间列表,从而保留了 memory。 List comprehension would be:列表理解将是:
print " ".join([str(i) for i in a])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.