def get_digits(str1):
c = ""
for i in str1:
if i.isdigit():
c += i
return c
Run Code Online (Sandbox Code Playgroud)
上面是我使用的代码,问题是它只返回字符串的第一个数字.为此,我必须保持for循环和return语句.谁知道如何解决?
谢谢.
Tar*_*ula 22
正如其他人所说的那样,你的缩进有一个语义问题,但是你不必编写这样的函数来做到这一点,更为pythonic的方法是:
def get_digits(text):
return filter(str.isdigit, text)
Run Code Online (Sandbox Code Playgroud)
在口译员:
>>> filter(str.isdigit, "lol123")
'123'
Run Code Online (Sandbox Code Playgroud)
当人们展示"更快"的方法时,总是自己测试一下:
from timeit import Timer
def get_digits1(text):
c = ""
for i in text:
if i.isdigit():
c += i
return c
def get_digits2(text):
return filter(str.isdigit, text)
def get_digits3(text):
return ''.join(c for c in text if c.isdigit())
if __name__ == '__main__':
count = 5000000
t = Timer("get_digits1('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits1")
print t.timeit(number=count)
t = Timer("get_digits2('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits2")
print t.timeit(number=count)
t = Timer("get_digits3('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits3")
print t.timeit(number=count)
~# python tit.py
19.990989106 # Your original solution
16.7035926379 # My solution
24.8638381019 # Accepted solution
Run Code Online (Sandbox Code Playgroud)
Ben*_*end 10
你的缩进有点笨拙(Python中的缩进非常重要).更好:
def get_digits(str1):
c = ""
for i in str1:
if i.isdigit():
c += i
return c
Run Code Online (Sandbox Code Playgroud)
使用更短的和更快的溶液发生器表达式:
''.join(c for c in my_string if c.isdigit())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39907 次 |
| 最近记录: |