Reputation: 55
I'm trying to figure out an easy way to take a string in a line from a file that is being read using readline(). Specifically, there are multiple integer values which is where I am running into issues:
10 20 30
I would like the values above to be converted into a list of separate integers:
[10, 20, 30]
The values would then be summed within a separate class. I'm certain there is something simple I could do here, but I'm just drawing a blank. Thanks in advance!
Here's more context as to what I am trying to do. I'm passing the integers into an updateMany method in my class:
vals = infile.readline()
a.updateMany(int(vals.split())
updateMany() takes the list and sums them, adding them to a list variable local to the class.
Upvotes: 1
Views: 166
Reputation: 55
Thanks everyone for your help and different ways of solving this. I ended up using the following to get my values:
intList = [int(i) for i in vals.split(sep=' ')]
a.updateMany(intList)
Cheers!
Upvotes: 0
Reputation: 8709
You van use map()
. It takes items from a list and applies given function upon them.
>>> string = "10 20 30"
>>> map(int, string.split())
[10, 20, 30]
Upvotes: 2
Reputation: 3782
If you just use space as separator, you can use split method of a string object:
>>> num_line = '10 20 30'
>>> [int(num) for num in num_line.split() if num]
[10, 20, 30]
If your separator is more than one char like ',' and '.' or space, you can use re.split():
>>> import re
>>> re_str = "[,. ]"
>>> num_line = '10, 20, 30.'
>>> [int(num) for num in re.split(re_str, num_line) if num]
[10, 20, 30]
Upvotes: 0
Reputation: 69182
You could use:
x = [int(i) for i in "10 20 30".split()]
then
sum(x)
Upvotes: 2
Reputation: 881605
For example:
thelist = [int(s) for s in thestring.split()]
Upvotes: 5