Printing an int list in a single line python3

前端 未结 10 1405
臣服心动
臣服心动 2020-12-03 01:16

I\'m new to python and I\'m trying to scan multiple numbers separated by spaces (let\'s assume \'1 2 3\' as an example) in a single line and add it to a list of int. I did i

10条回答
  •  天涯浪人
    2020-12-03 01:47

    You have multiple options, each with different general use cases.

    The first would be to use a for loop, as you described, but in the following way.

    for value in array:
        print(value, end=' ')
    

    You could also use str.join for a simple, readable one-liner using comprehension. This method would be good for storing this value to a variable.

    print(' '.join(str(value) for value in array))
    

    My favorite method, however, would be to pass array as *args, with a sep of ' '. Note, however, that this method will only produce a printed output, not a value that may be stored to a variable.

    print(*array, sep=' ')
    

提交回复
热议问题