我正在尝试遍历一个列表。每行包含三个数字。该列表可以尽可能长,但我只想检查前 21 行。我试过使用 islice,但我似乎无法正确使用它。
from sys import argv
script, filename = argv
f = open(filename)
while True:
line = f.readline()
fields = line.split(" ")
x = int(fields[0])
y = int(fields[1])
z = int(fields[2])
for n in range(1, z):
if n % x == 0 and n % y == 0:
print "FB",
elif n % x == 0:
print "F",
elif n % y == 0:
print "B",
else:
print n,
print line
if not line:
break
最佳答案
我不太清楚为什么你不能让 islice
工作。使用它的一个工作示例是:
import itertools
with open(filename, "r") as f:
for line in itertools.islice(f, 21):
fields = line.split(" ")
# Rest of your code here...
这可能是最简单的解决方案,因为您无需在代码中引入额外的复杂性即可获得相同的结果。
关于python - 无法将循环限制为 21 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26233170/