![](/img/trans.png)
[英]How can I separate and traverse data in a list of tuples in Python 2.6?
[英]How can I process data after a specific line in python 2.6?
我有一个脚本,该脚本基本上读取一个文本文件并创建8个列表。 如果它从第1行读取文件,则可以完美工作。我需要它开始从第177行到第352行(即最后一行)读取文本文件。
这是我的脚本和更改。 我没有收到任何错误,但也没有任何结果。 程序挂在那里没有响应:
f = open("Output1.txt", "r")
lines = [line.rstrip() for line in f if line != "\n"] #Get all lines, strip
newline chars, and remove lines that are just newlines.
NUM_LISTS = 8
groups = [[] for i in range(NUM_LISTS)]
listIndex = 0
for line in lines:
while line > 177: #here is the problem
if "Transactions/Sec for Group" not in line:
groups[listIndex].append(float(line))
listIndex += 1
if listIndex == NUM_LISTS:
listIndex = 0
value0 = groups[0]
value1 = groups[1]
value2 = groups[2]
value3 = groups[3]
value4 = groups[4]
value5 = groups[5]
value6 = groups[6]
value7 = groups[7]
json_file = 'json_global.json'
json_data = open(json_file)
data = json.load(json_data)
for var1 in range(0, 11):
a = value0[var1]
b = value1[var1]
c = value2[var1]
d = value3[var1]
e = value4[var1]
f = value5[var1]
g = value6[var1]
h = value7[var1]
var2 = var1 + 57
item = data[var2]['item']
cmd = data[var2]['command']
var1+= 1
print item, cmd, a, b, c, d, e, f, g, h)
line
包含每行的内容,而不是行号。 即使这样做,这也将失败,因为由于第一行的数字不大于177,所以您将跳过循环。这是一种执行所需操作的方法:
for linenumber, line in enumerate(lines, 1):
if linenumber > 177:
do_stuff(line)
enumerate()
接受一个可迭代的并返回(index, item)
元组的可迭代。 1
参数告诉它从什么索引开始; 它默认为0
。 if linenumber > 177:
要更改行号if linenumber > 177:
调整该行和行号。
完成此操作的另一种方法是使用itertools.islice()
, Anand S Kumar在回答中也提到了这一点。 这是使用islice()
的版本,该版本不会事先将整个文件读入内存:
from itertools import islice
with open('Output1.txt', 'r') as f:
lines = (line.rstrip() for line in f if line != '\n')
for line in islice(lines, 177, None):
do_stuff(line)
这将有效地对线进行切片,就像您完成了线[177:]一样(这是另一种解决方案)。
请注意,您未包括仅换行的行,因此文件中的行177与程序中的行177不同。
问题在于, lines
是中的行列表,因此当您执行以下操作时-
for line in lines:
该line
是一个字符串,而不是该行的索引,因此下一个while循环为true,因此应该进入无限循环,因为您永远不会在while循环内更改line
,并且条件始终为true。
我不建议您这样做,而是建议您使用itertools.islice
从177行迭代到结束。 范例-
import itertools
for line in itertools.islice(lines,177,None):
if "Transactions/Sec for Group" not in line:
groups[listIndex].append(float(line))
listIndex += 1
if listIndex == NUM_LISTS:
listIndex = 0
value0 = groups[0]
value1 = groups[1]
value2 = groups[2]
value3 = groups[3]
value4 = groups[4]
value5 = groups[5]
value6 = groups[6]
value7 = groups[7]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.