Home > Blockchain >  How can I split and map input like 'S1,10' to two variables one str and other integer
How can I split and map input like 'S1,10' to two variables one str and other integer

Time:06-17

I am reading an input 'S1,10'. First component is a string and second is an integer. They are separated by comma.

I have tried x = input().split(','). This creates a list ['S1','10']. How can I create a list ['S1', 10] where the second element is an integer?

I have solved this in a two step process. bp = input().split(',') bp[1] = int(bp[1])

Can it be done in a single step? How can we split with different datatypes?

CodePudding user response:

I mean, if you really want to force it, it can be done in a single line

x = [s if i == 0 else int(s) for i,s in enumerate(input().split(','))]

But at the end of the day, code is for humans to understand. If I were you I would keep what you have.

CodePudding user response:

Here is a solution using the zip() function. With this approach it is easy to vary which functions to apply to the parts of the split string.

x = [f(s) for f, s in zip([str, int], input().split(','))]
  • Related