简体   繁体   English

将浮点列表加入到 Python 中的空格分隔字符串中

[英]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.

相关问题 将字符串列表转换为以空格分隔的字符串 - Convert list of strings to space-separated string 将以空格分隔的整数求和为列表中的字符串 - Sum space-separated integers as string in a list 打印以空格分隔的元素列表 - Print a list of space-separated elements 如何在一个字符串中发现一个字符串的多次出现,并以空格分隔的列表返回其位置的索引? - How do I find multiple occurences of a string in a string and return the index of its location in a space-separated list? 将一列中的空格分隔字符串拆分为两列(int) - pandas python - splitting space-separated string in one column to two (int) columns - pandas python 用写线将列表列表写入文本文件,以空格分隔? - Write list-of-list to text file with writelines, space-separated? 在文件名中创建一个以空格分隔的选定字符列表 - Make a space-separated list of selected characters in a filename “ int()的无效文字”使用空格分隔的数字解析字符串 - “invalid literal for int()” parsing a string with space-separated numbers 在 python 中拆分 dataframe 中的空格分隔值列 - split column of space-separated values ​in dataframe in python 如何在 python 的数组中输入一个空格分隔的整数数组 append? - How to append an array of space-separated integers input in an array in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM