Python- lines_startswith代码

0 python docstring python-3.x python-3.4

以下是我必须完成的代码.所以,我想要的结果是读取文件(每一行),如果我在文件中读取的行的第一个字母与我选择的字母匹配,则返回列表中的行匹配.

def lines_startswith(file,letter):
    '''(file open for reading, str) -> list of str
    Return the list of lines from file that begin with letter. The lines should have the newline removed.
    Precondition:len(letter) == 1
    '''
    matches = []
    (blank)
    return matches
Run Code Online (Sandbox Code Playgroud)

我必须填写(空白)来完成代码.

这是我到目前为止,但我无法得到我需要的结果.

for line in file:
        if line[0] == 'letter':
            matches.append(line)
Run Code Online (Sandbox Code Playgroud)

我的代码出了什么问题?

unw*_*ind 5

这个:

if line[0] == 'letter':
Run Code Online (Sandbox Code Playgroud)

检查第一个字符line是否是6个字符的字符串'letter',这当然没有意义且永远不会成立.

你的意思是

if line[0] == letter:
Run Code Online (Sandbox Code Playgroud)

这将检查单个字符at是否与单个字符line[0]相同letter,这是您想要的.

更简洁的写作方式是:

matches = [line for line in file if line[0] == letter]
Run Code Online (Sandbox Code Playgroud)