【问题标题】:learnpython.org modules exerciselearnpython.org 模块练习
【发布时间】:2013-09-17 21:53:21
【问题描述】:

大家好,

[序言]:
我来自 BASH 脚本背景(还在那儿学习),我决定冒险学习另一种语言可能会有益于我的学习过程。对我来说,自然的选择似乎是 Python。我开始学习了一下,并且一直在学习 www.learnpython.org 上的练习。特别是Modules and Packages

[问题]:

Import模块重新print按字母顺序排序,模块中包含单词find的所有函数。

[试过]:

# 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() 函数的一部分完成的?以正确格式获得所需输出的好方法是什么?

【问题讨论】:

    标签: python python-2.7 module python-import


    【解决方案1】:

    您应该将结果收集到一个列表中,然后对它们进行排序:

    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
    
    
    results = []
    for element in dir(re):
        if element.startswith('find'):
            results.append(element)
    
    print sorted(results)
    

    或者,在一行中使用list comprehension

    import re
    
    print sorted([element for element in dir(re) if element.startswith('find')])
    

    如果单词find 可以出现在字符串中的任何位置,您应该使用in 而不是startswith()

    import re
    
    print sorted([element for element in dir(re) if 'find' in element])
    

    【讨论】:

    • 优秀的解决方案。第一个不被接受为问题的正确格式,但其他的工作得很好。感谢您在该领域的帮助。我仍然可以在评论部分使用一些反馈,但除此之外,太棒了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2015-05-01
    • 2023-03-11
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多