3

Suppose the input is: string integer integer. Now i need to map only the 2nd and 3rd input to integer.

name, d, j = input().split()
d = int(d)
j = int(j)

Is this the only way to do it?

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
rohegde7
  • 633
  • 9
  • 15

3 Answers3

4

You could also do this:

name, d, j = input().split()
d,j = map(int,[d,j])

But I don't really see the benefit. There's nothing wrong with what you already have. Remember, fewer lines of code is not a goal unto itself.

mypetlion
  • 2,415
  • 5
  • 18
  • 22
  • 3
    `Remember, fewer lines of code is not a goal unto itself.`, +1 for that. – Keyur Potdar Jan 26 '18 at 17:18
  • 1
    I suppose I should qualify that with "Unless you're doing a code golf challenge." Since Python is a fairly popular code golf language. – mypetlion Jan 26 '18 at 17:19
  • @mypetlion what's the difference between using ( ) vs [ ] for 2nd map parameter? I used both and both worked. eg: map(int, (x,y)) worked same as map(int, [x,y]) – rohegde7 Jan 26 '18 at 17:20
  • @rohegde7 Nothing, really. Personal preference. I'll typically default to `[]` for throwaway iterables like that, but use `()` if you like. For trivial situations like this, it's pretty rare that it will make a difference. By "rare" I mean that I can't think of any such situations off the top of my head. – mypetlion Jan 26 '18 at 17:22
  • 1
    @rohegde7, the `2nd map parameter` is an iterable. So it can be a list or a tuple or any other iterable. [Read this.](https://stackoverflow.com/a/10973804/7832176) – Keyur Potdar Jan 26 '18 at 17:25
1
name, d, j = [int(b) if i >=1 else b for i,b in enumerate(input().split())]
sophros
  • 14,672
  • 11
  • 46
  • 75
0

For the purely academic challenge of squeezing it into one line, you could use the singleton list/iterator trick:

name, d, j = next((x, *map(int, y)) for x, *y in ['john 3 4'.split()])

But pls never do this in production code ;)

user2390182
  • 72,016
  • 6
  • 67
  • 89