Print a list of space-separated elements in Python 3

前端 未结 4 1029
野趣味
野趣味 2020-11-28 04:55

I have a list L of elements, say natural numbers. I want to print them in one line with a single space as a separator. But I don\'t w

4条回答
  •  心在旅途
    2020-11-28 05:30

    Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

    The best way is to print joined string of numbers converted to strings.

    print(" ".join(list(map(str,l))))
    

    Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

    import time as t
    
    a, b = 10, 210000
    l = list(range(a, b))
    tic = t.time()
    for i in l:
        print(i, end=" ")
    
    print()
    tac = t.time()
    t1 = (tac - tic) * 1000
    print(*l)
    toe = t.time()
    t2 = (toe - tac) * 1000
    print(" ".join([str(i) for i in l]))
    joe = t.time()
    t3 = (joe - toe) * 1000
    print(" ".join(list(map(str, l))))
    toy = t.time()
    t4 = (toy - joe) * 1000
    print("Time",t1,t2,t3,t4)
    

    Result:

    Time 74344.76 71790.83 196.99 153.99

    The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

    Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

提交回复
热议问题