Converting a list of individually white-space separated strings into integers

61 views Asked by At

For a routine programming question, I took input from the user for a list using a raw input mode, as many times as a variable suggested. now i have a list of strings, in which each element of the list has a set of whitespace separated strings as shown:

['2 5 4', '3 7 8 9', '5 5 7 8 9 10']

Now, I want to convert the strings to a list of integers. In effect, I want the final list to look like this:

[ [2,5,3] , [3,7,8,9] , [5,5,7,8,9,10] ]

Also, to take the inputs from the used, I use this:

 print 'Enter the number of lists and mod value:'
    a, b = map(int, sys.stdin.readline().split())
    lst = []
    for i in range(a):
        v = []
        v = raw_input()
        lst.append(v)
    print lst

Is there a way to do this? I'm using Python 2.7 with PyCharm as editor. Any help would be appreciated.

3

There are 3 answers

1
Taohidul Islam On BEST ANSWER

Simply use list comprehension and split function.

  l = ['2 5 4', '3 7 8 9', '5 5 7 8 9 10']
  expected_list = [[int(j) for j in i.split()] for i in l]
  print(expected_list)

Output:

[[2, 5, 4], [3, 7, 8, 9], [5, 5, 7, 8, 9, 10]]
2
Rakesh On

Using a list comprehension & map

Ex:

l = ['2 5 4', '3 7 8 9', '5 5 7 8 9 10']
print( [map(int, i.split()) for i in l] )    #For py3 = print( [list(map(int, i.split())) for i in l] )

Output:

[[2, 5, 4], [3, 7, 8, 9], [5, 5, 7, 8, 9, 10]]
0
coder3521 On

Use a simple loop for iterating over the list:

list = ['2 5 4', '3 7 8 9', '5 5 7 8 9 10']
new_list = []
for each in list:
   s = each.split()
   numbers = [int(x) for x in s]
   new_list.append(numbers)