[英]Python parsing, convert string to list of integers
I'm using raw_input
for the user to type in an integer, for example '123456'
. 我正在使用
raw_input
为用户键入一个整数,例如'123456'
。
How do I convert the string number by number so I can put them in a list: [1,2,3,4,5]
? 如何按数字转换字符串编号,以便将它们放在列表中:
[1,2,3,4,5]
?
Is the concept the same for two numbers like 12
, 34
, 56
? 是概念同样为两个数字像
12
, 34
, 56
?
If you want to transform the string you read in from raw_input
to a list of int
... 如果您想将您从
raw_input
读取的字符串转换为int
列表,则可以使用...
number = raw_input("Number? ")
li = [int(i) for i in number]
There's only a little bit more work that you have to do to expand it to multiple digits, but I leave that as an exercise for the reader. 您只需要做一点点的工作即可将其扩展为多个数字,但我将其留给读者作为练习。
if user enter the numbers Consecutive you you can use the following list comprehension : 如果用户输入连续数字,则可以使用以下列表理解:
>>> num=raw_input ("enter the numbers : ")
enter the numbers : 123459
>>> l=[int(i) for i in num]
>>> l
[1, 2, 3, 4, 5, 9]
and for numbers with len 2 that uses ,
as separator you need to split the input string then convert it to int : 并与使用LEN 2号
,
作为分隔符,你需要拆分输入字符串然后将其转换为int:
>>> num=raw_input ("enter the numbers : ")
enter the numbers : 12,34,56
>>> l=[int(i) for i in num.split(',')]
>>> l
[12, 34, 56]
But there is another way , if you dont want to convert the numbers you can put your raw_input
function inside a loop : 但是还有另一种方法,如果您不想转换数字,可以将
raw_input
函数放入循环中:
>>> l=[]
>>> for i in range (5):
... l.append(int(raw_input('enter %dth number :'%i)))
...
enter 0th number :1
enter 1th number :5
enter 2th number :12
enter 3th number :56
enter 4th number :2345
>>> l
[1, 5, 12, 56, 2345]
and if you want to get number with len 2 from one input you can use slicing : 如果要从一个输入中获得len 2的数字,则可以使用切片:
>>> num=raw_input ("enter the numbers : ")
enter the numbers : 1234424
>>> [int(num[i:i+2]) for i in range(0,len(num),2)]
[12, 34, 42, 4]
s = '123456'
print(map(int,s))
s = '12,34,56'
print(map(int,s.split(",")))
[1, 2, 3, 4, 5, 6]
[12, 34, 56]
s = '123456'
print([int("".join(tup)) for tup in zip(s[::2],s[1::2])]
[12, 34, 56]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.