我编写了下面给出的代码:它的输出数据类型是整数,我希望这些整数在列表中。我是 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)
您可以使用列表推导来做到这一点。enumerate
为您提供每行的行号,1
在这种情况下从开始。不需要,.readlines()
因为迭代一个类似文件的文件会遍历每一行。
[line_no for line_no, line in enumerate(css,1) if "width" in line]
使用您的原始代码,您只需要添加两个新行:
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 的解决方案以了解这些构造的使用。
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")
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)