开发者

Typed input in python?

开发者 https://www.devze.com 2023-02-24 19:24 出处:网络
I need to input 3 integers form stdin and outut their sum. Here\'s what i do: (n,l,k) = raw_input().split()

I need to input 3 integers form stdin and outut their sum. Here's what i do:

(n,l,k) = raw_input().split()
print n + l + k

Of course, i get n,l,k string concatenation, so i change this a little:

(n,l,k) = raw_input().split()
print int(n) + int(l) + int(k)

Now it's ok. But is t开发者_JS百科here any way to set data type for the variables 'on the fly', so n,l,k became int whitout explicit reassigning for further use( i think of n = int(n) ) ?

UPDATE:

What if i need to input int, string, int (tuple items are of different types) ? THis means i can't do

(n,S,k) = [int(i) for i in raw_input().split()]

Any zip(), lambdas, accepting types?

Thanks in advance, Ilya


Not really. You need to tell it what you want. There are some more succinct ways to do that in Python.

(n,l,k) = [int(v) for v in raw_input().split()]

This is generally true of all user input. It must be validated and converted to what the rest of your program expects.

Oh, well you can use the type objects to list the types you want. Use the fact that variables are references and you can reference a type object with a variable as well.

print [t(tok) for (t, tok) in zip((int, str, int), raw_input().split())]


I think this does what you want:

(n,l,k) = [f(i) for i,f in zip(raw_input().split(),(int,str,int))]

So we're zipping together the input values and a list (or rather a tuple) of functions that will convert the input to the required type.

What you can't do is somehow tell Python that n should always contain an int and get it to convert things automatically. Variables in Python are just names which are bound to a value - any value - and so you can't add any state to them beyond the value they are bound to.


Can you handle the input variables as a dict?

var_types = { 'n': int, 'S': str, 'k': int } # dict, so no given order
var_order = ('n', 'S', 'k') # a tuple with a given order of variables

input_var = dict((k, var_types[k](v)) for k, v in zip(var_order, raw_input().split()))

For given string 12 abc 34 it returns:

{'S': 'abc', 'k': 34, 'n': 12}

This way you can define the var_types at one place centrally for all input variables. The var_order will be defined for each raw_input dialogue.

0

精彩评论

暂无评论...
验证码 换一张
取 消