简体   繁体   English

如何在python 3中编写每一行?

[英]How to write every second line in python 3?

def every_second_line(report):
    """ (Open File for reading) -> list of str

    Return a list containing every second line (with leading and trailing
    whitespace removed) in report, starting with the first line.
    """
    list=[]
    for line in report:
        list.append(line.strip)
    report.readline()
    return list

I just came across this code while I was reviewing for my exam. 我在审查我的考试时遇到了这段代码。 Can someone please tell me why this code is not working? 有人可以告诉我为什么这段代码不起作用? Thanks in advance! 提前致谢!

The minimal change to your code is just to put report.readline() inside the for loop. 对代码的最小更改只是将report.readline()放在for循环中。

for line in report:
    lst.append(line.strip())
    report.readline()

You could also use next(report) (which works for all iterators, not just file objects) instead of report.readline() . 您还可以使用next(report) (适用于所有迭代器,而不仅仅是文件对象)而不是report.readline()

Note that if your file has an odd number of lines, that report.readline() might throw a StopIteration error (or is it EOFError ?) Best to catch that. 请注意,如果您的文件具有奇数行,则该report.readline()可能会抛出StopIteration错误(或者是EOFError ?)最好抓住它。

for line in report:
    lst.append(line.strip())
    try:
        next(report)
    except (StopIteration, EOFError): # because I don't remember which it throws
        break # leave the for loop

Or as JuniorCompressor notes in the comments, you can use the optional argument to next to ignore completely 或者作为JuniorCompressor在注释中注释,您可以使用next的可选参数来完全忽略

for line in report:
    lst.append(line.strip())
    next(report, None)

You can slice using itertools.islice with a step of 2 using map to str.strip each line: 你可以使用itertools.islice切片,步骤为2,使用map to str.strip每一行:

from itertools import islice

with open(fle) as f:
    print(list(map(str.strip,islice(f,0,None,2))))

If you want every second line from the second start from 1: 如果你想从第二个开始的第二行开始:

 print(list(map(str.strip,islice(f,1,None,2))))

According to your specification you are meant to open a file which I don't see you doing. 根据您的规范,您打算打开一个我不认为您正在做的文件。

In your own code if you actually have a file object passed you just need to call next on the file object and actually call strip with parens: 在您自己的代码中,如果您实际上已经传递了一个文件对象,您只需要在文件对象上调用next并实际调用带有parens的strip

    lst=[]
    for line in report:
        lst.append(line.strip()) # to call strip you need parens
        next(report,"")
    return lst

Put next before lst.append if you want every second line starting from the second. next之前lst.append如果你想从第二个开始每隔第二行。 next takes a default value so we pass an empty string to avoid a stopIteration error in case we run out of lines before and still call next. next接受一个默认值,所以我们传递一个空字符串以避免stopIteration错误,以防我们之前用完线路并仍然调用next。

try this to get every 2nd element in list: 尝试这个来获取列表中的每个2nd元素:

for line in report[::2]:

If you dont want 1st line 如果你不想要1st line

for line in report[1::2]:

Considering if report is generator object : 考虑report是否为generator object

Simply call list 只需拨打电话list

for line in list(report)[::2]:

IF report must act as a generator (huge file), then 因此,IF报告必须充当generator (大文件)

try:
    for x in report:
        line = next(report)
        list.append(line.strip()) #dont use list as variable name
except StopIteration:
    pass

list=[] for line in report: list.append(line.strip()) report.readline() return list This is the right version. list = []用于报告中的行:list.append(line.strip())report.readline()返回列表这是正确的版本。 Thanks! 谢谢! Guys 伙计们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM