0

我编写了下面给出的代码:它的输出数据类型是整数,我希望这些整数在列表中。我是 python 新手。请建议如何做。

lineNo = 0
css = open("/Users/john/Work/html/Ribbon/header.css")  
for line in css.readlines():
    lineNo = lineNo + 1
    if "width" in line:
        print(lineNo)
4

4 回答 4

3

您可以使用列表推导来做到这一点。enumerate为您提供每行的行号,1在这种情况下从开始。不需要,.readlines()因为迭代一个类似文件的文件会遍历每一行。

[line_no for line_no, line in enumerate(css,1) if "width" in line]
于 2012-05-16T10:55:47.583 回答
1

使用您的原始代码,您只需要添加两个新行:

lineNo = 0
css = open("/Users/john/Work/html/Ribbon/header.css")  
myList = []  # create an empty list
for line in css.readlines():
    lineNo = lineNo + 1
    if "width" in line:
        print(lineNo)
        myList.append(lineNo)  # add your item to the list

一旦您对 Python 感到更舒服,您可能会考虑将列表理解enumerate结合起来,以自动获取行数来代替原始方法。请参阅@jamylak 的解决方案以了解这些构造的使用。

同时,这里是对列表和 Python文档的非正式介绍

于 2012-05-16T10:55:41.967 回答
0
def extractWidth(line):
    return line  # your code here

def loadWidths(path):
    with open(path) as f:
        return [extractWidth(line) for line in f if ("width in line")]

loadWidths("/Users/john/Work/html/Ribbon/header.css")
于 2012-05-16T12:12:02.917 回答
0
lineNo = []
css = open("/path/to/stylesheet.css")  
for i,line in enumerate(css.readlines(), start=1):
        if "width" in line:
            print (i, line)
            lineNo.append(i)


print (lineNo)
于 2012-05-17T03:09:22.763 回答