質問

I'm new to Python and I'm sure that there's a method to do this that I don't know about. I checked around for my question, and there are many similar ones but I didn't find exactly mine.

The string I have is:

"Arkansas 40\n Washington 83\n North Dakota 49\n New Jersey 24"

What I want to do is add just the numbers in the string together.

I've written a function that does this using the "try" statement, but "try" requires something to be written to the "except" portion of the indent, and I would just like it to simply discard any exceptions silently.

The output I'm looking for is:

196

(EDIT) Wow - there are a LOT of ways to do this, clearly. I picked the best answer for the very simple task I was trying to accomplish.

Mainly, what I needed to know about was "isdigit()", and when using try statements, the "pass" keyword for exception.

役に立ちましたか?

解決

This works:

s = "Arkansas 40\n Washington 83\n North Dakota 49\n New Jersey 24"

sum(int(n) for n in s.split() if n.isdigit())

196

Basically the .isdigit() method does the trick here. No need for a try/except as if there are no numbers in the string, no n will meet the isdigit() condition, and sum will return 0.

他のヒント

>>> s = "Arkansas 40\n Washington 83\n North Dakota 49\n New Jersey 24"
>>> sum([int(x.split()[-1]) for x in s.split('\n')])
196

Something like this

import re
tot = 0
s = "Arkansas 40\n Washington 83\n North Dakota 49\n New Jersey 24"
for line in s.split('\n'):
    ma = re.search('(\d+)', line)
    if ma:
        tot += ma.group(1)
print tot

So what you need to do first is extract the numbers from the string. You can split the string out into chunks using String.split(), and then just test if each is a number by iterating through them, returning only the ones that are integers. For example, if you have the string s:

[int(i) for i in s.split('\n') if i.isdigit()]

will create an array of integers. Then all you have to do is sum them up, and there's your answer.

wonderful opportunity to abuse map,filter & reduce

print reduce(lambda x,y: x+y, 
             map(lambda x: int(x), 
                 filter(lambda x: x.isdigit(), 
                        re.split(' |\n',s))))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top