Read two variables in a single line with Python

2019-01-24 06:58发布

I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?

I'm looking for the equivalent of:

scanf("%d%d", &i, &j); // accepts "10 20\n"

One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way?

This is not for live use. Just for learning..

标签: python input
7条回答
做自己的国王
2楼-- · 2019-01-24 07:15

No, the usual way is raw_input().split()

In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings

Don't use input() for that. Consider what happens if the user enters

import os;os.system('do something bad')

查看更多
We Are One
3楼-- · 2019-01-24 07:17

Firstly read the complete line into a string like

    string = raw_input()

Then use a for loop like this

    prev = 0 
    lst = []
    index = 0 
    for letter in string :
        if item == ' ' or item == '\n' :
            lst.append(int(string[prev:index])
            prev = index + 1

This loop takes a full line as input to the string and processes the parts in it individually and then appends the numbers to the list - lst after converting them to integers .

查看更多
爷的心禁止访问
4楼-- · 2019-01-24 07:24

or you can do this

input_user=map(int,raw_input().strip().split(" "))
查看更多
Anthone
5楼-- · 2019-01-24 07:26

You can also read from sys.stdin

import sys

a,b = map(int,sys.stdin.readline().split())
查看更多
霸刀☆藐视天下
6楼-- · 2019-01-24 07:31

You can also use this method for any number of inputs. Consider the following for three inputs separated by whitespace:

import sys

S = sys.stdin.read()
S = S.split()
S = [int(i) for i in S]
l = S[0]
r = S[1]
k = S[2]
查看更多
劫难
7楼-- · 2019-01-24 07:35

you can read 2 int values by using this in python 3.6.1

n,m = map(int,input().strip().split(" "))
查看更多
登录 后发表回答