在 Python 中解析数字 [英] Parsing numbers in Python

查看:53
本文介绍了在 Python 中解析数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想接受这样的输入10 12

13 14

15 16

...

如何将此输入作为两个不同的整数,以便我可以在 python 中将它们相乘每 10 和 12 之后有换行符

解决方案

我不确定我是否理解您的问题,您似乎想解析两个由空格分隔的 int.

在 python 中,你可以:

s = raw_input('插入2个以空格分隔的整数:')a,b = [int(i) for i in s.split(' ')]打印 a*b

说明:

s = raw_input('插入2个以空格分隔的整数:')

raw_input 接受您输入的所有内容(直到您按 Enter 键)并将其作为字符串返回,因此:

<预><代码>>>>raw_input('插入2个以空格分隔的整数:')插入 2 个以空格分隔的整数:10 12'10 12'

在s中你现在有'10 12',两个int用空格隔开,我们在空格处用

分割字符串<预><代码>>>>s.split(' ')['10', '12']

现在你有一个字符串列表,你想把它们转换成 int,所以:

<预><代码>>>>[int(i) for i in s.split(' ')][10, 12]

然后将列表中的每个成员分配给一个变量(a 和 b),然后进行乘积 a*b

i want to take inputs like this 10 12

13 14

15 16

..

how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline

解决方案

I'm not sure I understood your problem very well, it seems you want to parse two int separated from a space.

In python you do:

s = raw_input('Insert 2 integers separated by a space: ')
a,b = [int(i) for i in s.split(' ')]
print a*b

Explanation:

s = raw_input('Insert 2 integers separated by a space: ')

raw_input takes everything you type (until you press enter) and returns it as a string, so:

>>> raw_input('Insert 2 integers separated by a space: ')
Insert 2 integers separated by a space: 10 12
'10 12'

In s you have now '10 12', the two int are separated by a space, we split the string at the space with

>>> s.split(' ')
['10', '12']

now you have a list of strings, you want to convert them in int, so:

>>> [int(i) for i in s.split(' ')]
[10, 12]

then you assign each member of the list to a variable (a and b) and then you do the product a*b

这篇关于在 Python 中解析数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆