1

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.

2
  • Show us what you tried and add some more examples. Commented Jan 19, 2015 at 5:26
  • Sorry - added more to the above. TY! Commented Jan 19, 2015 at 5:37

5 Answers 5

5

For example:

thelist = [int(s) for s in thestring.split()]
Sign up to request clarification or add additional context in comments.

Comments

2

You could use:

x = [int(i) for i in "10 20 30".split()]

then

sum(x)

Comments

2

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]

Comments

0

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]

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.