简体   繁体   English

如果列表中给出了行,如何从文件中打印行?

[英]How to print lines from file if lines are given in list?

I'm fairly new to python (using 2.7) so I realize this might be an obvious solution.我对python(使用2.7)相当陌生,所以我意识到这可能是一个明显的解决方案。 I'm writing this more to work through the issue on "paper" so to speak.可以这么说,我写这篇文章是为了解决“纸”上的问题。

I have a file containing several different instances of a phrase (phrase="xy Coordinates") and successfully created lists containing the start and end lines of each instance of these coordinates.我有一个文件,其中包含几个不同的短语实例(phrase="xy Coordinates"),并成功创建了包含这些坐标每个实例的开始行和结束行的列表。 My question is, now that I have these lists how would I iterate over them to print each line of the coordinate?我的问题是,既然我有了这些列表,我将如何遍历它们以打印坐标的每一行?

This is what I have so far.这就是我到目前为止所拥有的。

def printCart(filename):
    with open(filename) as f:
            CStart=[]
            CEnd=[]
            for i in range(len(slist)):
                    start=slist[i]+5
                    end=start+int(num)-1
                    CStart.append(start)
                    CEnd.append(end)
            return CStart,CEnd

In order to iterate through a list and print each element, you can do (suppose your list is called CStart):为了遍历列表并打印每个元素,您可以执行以下操作(假设您的列表称为 CStart):

for element in CStart:
    print element

It was a pretty easy fix, now I just need to figure out how to give each list a different iterative name.这是一个非常容易解决的问题,现在我只需要弄清楚如何给每个列表一个不同的迭代名称。 Typing out the problem actually helps!输入问题实际上有帮助!

def finalprint(filename):
    with open(filename) as f:
            lines=f.readlines()
            for line in lines:
                    cart=[]
                    for element in CSlist:
                            if lines[element] in CElist:
                                    break
                            else:
                                    c=lines[element].strip().split()
                                    del c[0:1]
                                    cart.append(c)
    return cart

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

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