在 Python 中解析数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/959412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:09:26  来源:igfitidea点击:

Parsing numbers in Python

pythonparsing

提问by Hick

i want to take inputs like this 10 12

我想接受这样的输入 10 12

13 14

13 14

15 16

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

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

回答by Andrea Ambu

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

我不确定我是否很好地理解了您的问题,您似乎想解析两个与空格分开的 int。

In python you do:

在 python 中,你可以:

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 接受您输入的所有内容(直到您按 Enter 键)并将其作为字符串返回,因此:

>>> 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 中你现在有 '10 12',两个 int 被一个空格隔开,我们在空格处分割字符串

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

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

现在您有一个字符串列表,您想将它们转换为 int,因此:

>>> [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

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

回答by Nicolas Dumazet

f = open('inputfile.txt')
for line in f.readlines():
    # the next line is equivalent to:
    # s1, s2 = line.split(' ')
    # a = int(s1)
    # b = int(s2)
    a, b = map(int, line.split(' '))
    print a*b

回答by Dario

You could use regular expressions (re-module)

您可以使用正则表达式(re-module)

import re

test = "10 11\n12 13" # Get this input from the files or the console

matches = re.findall(r"(\d+)\s*(\d+)", test)
products = [ int(a) * int(b)  for a, b in matches ]

# Process data
print(products)