learnpython.org模块练习 社区你好,
[序言]:learnpython.org模块练习 社区你好,,python,python-2.7,module,python-import,Python,Python 2.7,Module,Python Import,[序言]: 我来自BASH脚本编写背景(还在那里学习),并决定冒险学习另一种语言可能有助于我的学习过程。我的自然选择似乎是Python。我开始学习一点,一直在学习www.learnpython.org上的练习。特别是,. [问题]: 导入模块重新和打印按字母顺序排序,模块中包含单词的所有函数都会查找 [尝试]: # import the module. import re # store output of dir(re) in reLST as string list. ''' I beli
我来自BASH脚本编写背景(还在那里学习),并决定冒险学习另一种语言可能有助于我的学习过程。我的自然选择似乎是Python。我开始学习一点,一直在学习www.learnpython.org上的练习。特别是,. [问题]:
导入
模块重新和打印
按字母顺序排序,模块中包含单词的所有函数都会查找
[尝试]:
# import the module.
import re
# store output of dir(re) in reLST as string list.
''' I believe that's what happens, correct? '''
reLST = dir(re)
# iterate over reLST and assign m strings matching word containing find.
for element in reLST:
m = re.match("(find\w+)", element)
# Here it prints out the matches, but only using the function .groups()
''' Won't work using print sorted(m) ---why? '''
# Found tutorial online, but no real understanding of .groups() function use.
if m:
print sorted(m.groups())
[预期输出]:['findall','finditer'] [我的输出]:
['findall']
['finditer'] [问题]:
从技术上讲,该代码可以工作并输出从
dir(re)
抓取的所有字符串,但在新行上。我猜这是作为.groups()
函数的一部分完成的?以正确的格式获得所需输出的好方法是什么 您应该在列表中收集结果,然后对其进行排序:
import re
results = []
for element in dir(re):
m = re.match("(find\w+)", element)
if m:
results.append(m.group(1))
print sorted(results)
此外,您可以使用startswith()
,而不是re
:
或者,在一行中使用列表理解
:
import re
print sorted([element for element in dir(re) if element.startswith('find')])
如果单词find
可以位于字符串中的任何位置,则应在中使用,而不是startswith()
:
您应该在列表中收集结果,然后对其进行排序:
import re
results = []
for element in dir(re):
m = re.match("(find\w+)", element)
if m:
results.append(m.group(1))
print sorted(results)
此外,您可以使用startswith()
,而不是re
:
或者,在一行中使用列表理解
:
import re
print sorted([element for element in dir(re) if element.startswith('find')])
如果单词find
可以位于字符串中的任何位置,则应在中使用,而不是startswith()
:
优秀的解决方案。第一种格式不被认为是解决问题的正确格式,但其他格式效果很好。谢谢你在这方面的帮助。我仍然可以在评论部分使用一些反馈,但除此之外,太棒了!优秀的解决方案。第一种格式不被认为是解决问题的正确格式,但其他格式效果很好。谢谢你在这方面的帮助。我仍然可以在评论部分使用一些反馈,但除此之外,太棒了!