[英]Convert list of floats to comma separated string | Python
Given a list of floats :给定一个浮动列表:
my_list = [0.3, 0.11, -0.9]
I want a string literal object:我想要一个字符串文字 object:
my_string = "0.3, 0.11, -0.9"
Attempt:试图:
print(', '.join(inputs))
> TypeError: sequence item 0: expected str instance, float found
The compact way:紧凑的方式:
l = [0.3, 0.11, -0.9]
print (str(l)[1:-1])
Output: Output:
0.3, 0.11, -0.9
Still, to be used with caution:).不过,要谨慎使用:)。 The "regular" way would be: “常规”方式是:
print (', '.join([str(x) for x in l]))
Try this:尝试这个:
print(' , '.join(str(x) for x in [0.3, 0.11, -0.9]))
Arguably, the easiest way would be to do:可以说,最简单的方法是:
my_string = str(my_list)[1:-1]
This takes my_list
, converts it into a string, and takes the characters from 1)leaving the first character at 0) to -1 (the end character is not taken)这需要my_list
,将其转换为字符串,并将字符从 1) 保留第一个字符为 0) 到 -1 (不使用结束字符)
A more pythonic way is to use map
to first convert all the float
values to str
, and then use the function join
to concatenate into a string.一种更map
首先将所有float
值转换为str
,然后使用 function join
连接成一个字符串。
print(', '.join(map(str, my_list)))
This prints 0.3, 0.11, -0.9
when my_list = [0.3, 0.11, -0.9]
当my_list = [0.3, 0.11, -0.9]
时打印0.3, 0.11, -0.9
-0.9
you can use join function of string like this:你可以使用这样的字符串加入 function :
first you have to convert float to str首先你必须将 float 转换为 str
my_string = ', '.join([str(i) for i in my_list])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.