将由空格分隔的整数字符串更改为int列表 [英] Change a string of integers separated by spaces to a list of int
本文介绍了将由空格分隔的整数字符串更改为int列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何制作
x ='1 2 3 45 87 65 6 8'
>>> foo(x)
[1,2,3,45,87,65,6,8]
我完全陷入困境,如果按索引进行,那么超过1位的数字将被分解。请帮助。
解决方案
您可以将列表理解与。split()方法:
x = [int(i)for i in x.split()]
或者你可以使用 map
以及:
x = list(map(int,x。 split()))
这将创建一个列表
of int
如果你想要整数的话。
或者只是使用 .split ()
获取字符串列表:
x = x.split()
如果你想创建一个 str
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 index, then the numbers with more than 1 digit will be broken down. Help please.
解决方案
You can use a list comprehension in combination with the .split() method:
x = [int(i) for i in x.split()]
Alternatively you can use map
aswell:
x = list(map(int, x.split()))
This will create a list
of int
's if you want integers.
or just use .split()
for a list of strings:
x = x.split()
If you want to create a list of str
这篇关于将由空格分隔的整数字符串更改为int列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文