String of numbers to a list of integers?

后端 未结 4 1813
抹茶落季
抹茶落季 2021-01-27 11:41

I\'ve been presented with the task of turning a string of mixed numbers (\"1 3 5 8 10\"), for example, and my goal is to put these numbers into a list as integers.

I ha

4条回答
  •  -上瘾入骨i
    2021-01-27 12:13

    First, numbers.split(" ") on its own isn't doing anything useful. Assign it to a variable. Also, if you give no parameters, it will always split on spaces, so you can use that.

    nums = numbers.split()
    

    With that, you should use for num in nums to loops over the split elements rather than looping over characters of the input string.

    In any case, you can shorten all of this by using a list-comprehension to apply that int function and return the list of integers.

    And you've defined a function, so you should return the value, not only print it.

    nums = [int(s) for s in numbers.split()] 
    return nums
    

    And then you would print(iq_test("1 2 3 10"))

提交回复
热议问题