I want to write this code in more pythonic way. Have you any idea how I can do this?
def counter():
for x in self.get_xs():
total_x = 0
result = (re.sub('[^0-9]', '', x))
for number in result:
total_x += int(number)
yield(total_x)
You can calculate the sum using sum()
and a generator expression. If the iterable passed to sum()
is empty(ie re.sub()
returned ''
) then it will simply return the default start
value 0.
def counter():
r = re.compile('[^0-9]')
for x in self.get_xs():
yield sum(int(number) for number in r.sub('', x))
In Python 3.3+ you can use yield from
:
def counter():
r = re.compile('[^0-9]')
yield from (sum(map(int, r.sub('', x))) for x in self.get_xs())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.