【发布时间】:2016-07-20 10:44:14
【问题描述】:
在 Python 中使用 DropWhile 进行练习,并且遇到了一些困难。
例如,如果这是文件中的行:
Test1
Test2
Test3
Test4
Test5
Test6
Test7
Test8
Test9
Test10
我想把 Test5 和 Test8 之间的界限拉出来。
我知道如何以另一种方式执行此操作(对于文件中的行...获取最后一行...如果行> 5 ....如果行
我尝试了几种不同的方法,但似乎无法让它发挥作用:
例如
dataset = open(sys.argv[1]).readlines()
def print_out(line):
if int(line.strip()[-1]) > 5:
if int(line.strip()[-1]) < 8:
return True
else:
return False
for line in dropwhile(lambda line: print_out(line) == True, dataset):
print line.strip()
这不行,所有行都打印出来了。
我尝试在 dropwhile 行中使用长 lambda 表达式而不是使用单独的函数的另一种方法,但是当我做了这样的事情时:
for line in dropwhile(lambda line: 5 < int(line.strip()[-1]) < 8, dataset):
如果我只有一个表达式(即 int(line.strip()[-1]) > 5 或 int(line.strip()[-1])
我想知道是否有人可以向我展示一种 Python 方式,使用 DropWhile,在我的测试数据集中拉出 Test5 和 Test8 之间的线?
【问题讨论】: