Change a string of integers separated by spaces to a list of int

后端 未结 6 1033
不知归路
不知归路 2020-12-25 11:33

How do i make something like

x = \'1 2 3 45 87 65 6 8\'

>>> foo(x)
[1,2,3,45,87,65,6,8]

I\'m completely stuck, if i do it by inde

6条回答
  •  星月不相逢
    2020-12-25 12:04

    The most simple solution is to use .split()to create a list of strings:

    x = x.split()
    

    Alternatively, you can use a list comprehension in combination with the .split() method:

    x = [int(i) for i in x.split()]
    

    You could even use map map as a third option:

    x = list(map(int, x.split()))
    

    This will create a list of int's if you want integers.

提交回复
热议问题