Get a list of numbers as input from the user

前端 未结 17 1130
生来不讨喜
生来不讨喜 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:17
    k = []
    i = int(raw_input('enter the number of values in the list '))
    l = 0
    while l < i:
        p = raw_input('enter the string ')
        k.append(p)
        l= l+1
    
    
    print "list is ", k
    
    0 讨论(0)
  • 2020-11-21 23:21

    It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:

    Python 3:

    s = input()
    numbers = list(map(int, s.split()))
    

    Python 2:

    s = raw_input()
    numbers = map(int, s.split())
    
    0 讨论(0)
  • 2020-11-21 23:21

    try this one ,

    n=int(raw_input("Enter length of the list"))
    l1=[]
    for i in range(n):
        a=raw_input()
        if(a.isdigit()):
            l1.insert(i,float(a)) #statement1
        else:
            l1.insert(i,a)        #statement2
    

    If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.

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

    You can use this function (with int type only) ;)

    def raw_inputList(yourComment):
         listSTR=raw_input(yourComment)     
         listSTR =listSTR[1:len(listSTR)-1]
         listT = listSTR.split(",")
         listEnd=[]
         for caseListT in listT:
              listEnd.append(int(caseListT))
         return listEnd
    

    This function return your list (with int type) !

    Example :

    yourList=raw_inputList("Enter Your List please :")
    

    If you enter

    "[1,2,3]" 
    

    then

    yourList=[1,2,3]          
    
    0 讨论(0)
  • 2020-11-21 23:25

    Another way could be to use the for-loop for this one. Let's say you want user to input 10 numbers into a list named "memo"

    memo=[] 
    for i in range (10):
        x=int(input("enter no. \n")) 
        memo.insert(i,x)
        i+=1
    print(memo) 
    
    0 讨论(0)
提交回复
热议问题