String of numbers to a list of integers?

后端 未结 4 1810
抹茶落季
抹茶落季 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条回答
  • 2021-01-27 11:56
    def iq_test(numbers):
        nums = []
        for num in numbers.split():
            nums.append(int(num)) 
    

    I guess ... you could(and probably should) just do a list comprehension instead

     nums = [int(num) for num in numbers.split()]
    
    0 讨论(0)
  • 2021-01-27 12:02

    You're using wrong array for iteration and also doing some wrong conversions:

    def iq_test(numbers):
        print(numbers)
        nums = []
        for number in numbers.split(" "):
             nums.append(int(number))
        print(nums)
    
    0 讨论(0)
  • 2021-01-27 12:07

    You can use regular expressions:

    import re
    s = "1 3 5 8 10"
    final_data = list(map(int, re.findall('\d+', s)))
    print(final_data)
    

    Output:

    [1, 3, 5, 8, 10]
    
    0 讨论(0)
  • 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"))

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