Get a list of numbers as input from the user

前端 未结 17 1129
生来不讨喜
生来不讨喜 2020-11-21 22:26

I tried to use raw_input() to get a list of numbers, however with the code

numbers = raw_input()
print len(numbers)

the input

相关标签:
17条回答
  • 2020-11-21 23:11
    num = int(input('Size of elements : '))
    arr = list()
    
    for i in range(num) :
      ele  = int(input())
      arr.append(ele)
    
    print(arr)
    
    0 讨论(0)
  • 2020-11-21 23:13

    You can use .split()

    numbers = raw_input().split(",")
    print len(numbers)
    

    This will still give you strings, but it will be a list of strings.

    If you need to map them to a type, use list comprehension:

    numbers = [int(n, 10) for n in raw_input().split(",")]
    print len(numbers)
    

    If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use eval

    0 讨论(0)
  • 2020-11-21 23:14

    In Python 3.x, use this.

    a = [int(x) for x in input().split()]
    

    Example

    >>> a = [int(x) for x in input().split()]
    3 4 5
    >>> a
    [3, 4, 5]
    >>> 
    
    0 讨论(0)
  • 2020-11-21 23:15

    eval(a_string) evaluates a string as Python code. Obviously this is not particularly safe. You can get safer (more restricted) evaluation by using the literal_eval function from the ast module.

    raw_input() is called that in Python 2.x because it gets raw, not "interpreted" input. input() interprets the input, i.e. is equivalent to eval(raw_input()).

    In Python 3.x, input() does what raw_input() used to do, and you must evaluate the contents manually if that's what you want (i.e. eval(input())).

    0 讨论(0)
  • 2020-11-21 23:15

    I think if you do it without the split() as mentioned in the first answer. It will work for all the values without spaces. So you don't have to give spaces as in the first answer which is more convenient I guess.

    a = [int(x) for x in input()]
    a
    

    Here is my ouput:

    11111
    [1, 1, 1, 1, 1]
    
    0 讨论(0)
  • 2020-11-21 23:17

    you can pass a string representation of the list to json:

    import json
    
    str_list = raw_input("Enter in a list: ")
    my_list = json.loads(str_list)
    

    user enters in the list as you would in python: [2, 34, 5.6, 90]

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