Parsing numbers in Python

2019-05-18 12:10发布

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

3条回答
放荡不羁爱自由
2楼-- · 2019-05-18 12:29

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

查看更多
3楼-- · 2019-05-18 12:47
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
查看更多
孤傲高冷的网名
4楼-- · 2019-05-18 12:48

You could use regular expressions (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)
查看更多
登录 后发表回答