在Python中将float list连接到以空格分隔的字符串中

时间:2022-10-14 03:34:35

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?

如何将元素(单独)转换为字符串,而不必遍历所有元素,从而加入所有元素?

2 个解决方案

#1


62  

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)

See the documentation of the syntax of format specifiers.

请参阅格式说明符语法的文档。

#2


1  

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. List comprehension would be:

与不生成第二中间列表的列表理解相比,该生成器具有优势,从而保留了存储器。列表理解将是:

print " ".join([str(i) for i in a])

#1


62  

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)

See the documentation of the syntax of format specifiers.

请参阅格式说明符语法的文档。

#2


1  

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. List comprehension would be:

与不生成第二中间列表的列表理解相比,该生成器具有优势,从而保留了存储器。列表理解将是:

print " ".join([str(i) for i in a])