Join float list into space-separated string in Python

后端 未结 2 1910
-上瘾入骨i
-上瘾入骨i 2021-02-03 19:27

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         


        
2条回答
  •  伪装坚强ぢ
    2021-02-03 20:10

    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])
    

提交回复
热议问题