Printing an int list in a single line python3

前端 未结 10 1297
臣服心动
臣服心动 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:26

    For python 2.7 another trick is:

    arr = [1,2,3]
    for num in arr:
      print num,
    # will print 1 2 3
    
    0 讨论(0)
  • 2020-12-03 01:29

    Try using join on a str conversion of your ints:

    print ' '.join(str(x) for x in array)
    
    0 讨论(0)
  • 2020-12-03 01:33

    these will both work in Python 2.7 and Python 3.x:

    >>> l = [1, 2, 3]
    >>> print(' '.join(str(x) for x in l))
    1 2 3
    >>> print(' '.join(map(str, l)))
    1 2 3
    

    btw, array is a reserved word in Python.

    0 讨论(0)
  • 2020-12-03 01:35

    You want to say

    for i in array:
        print(i, end=" ")
    

    The syntax i in array iterates over each member of the list. So, array[i] was trying to access array[1], array[2], and array[3], but the last of these is out of bounds (array has indices 0, 1, and 2).

    You can get the same effect with print(" ".join(map(str,array))).

    0 讨论(0)
  • 2020-12-03 01:38

    Yes that is possible in Python 3, just use * before the variable like:

    print(*list)
    

    This will print the list separated by spaces.

    (where * is the unpacking operator that turns a list into positional arguments, print(*[1,2,3]) is the same as print(1,2,3), see also What does the star operator mean, in a function call?)

    0 讨论(0)
  • 2020-12-03 01:38

    Maybe this code will help you.

    >>> def sort(lists):
    ...     lists.sort()
    ...     return lists
    ...
    >>> datalist = [6,3,4,1,3,2,9]
    >>> print(*sort(datalist), end=" ")
    1 2 3 3 4 6 9
    

    you can use an empty list variable to collect the user input, with method append(). and if you want to print list in one line you can use print(*list)

    0 讨论(0)
提交回复
热议问题