我有一个文本文件,其中包含:
I like potatoes
Potatoes are good
Potatoes contain starch我想测试每个句子是否按字典序排列。
如果句子是,我想让它输出"This is in lexicographic order“
我不太确定该怎么做。
发布于 2015-08-07 11:43:45
一种方法是读取文件,拆分行,将行按顺序排列,然后检查顺序是相同还是不同。
这可能不是最有效的方法,但可以工作:
with open('potatoes.txt') as potatoes:
potato_lines = potatoes.readlines()
print sorted(potato_lines) == potato_linesthis question的答案向您展示了如何在不排序的情况下进行检查。
例如,this answer提供了一种简洁的方式来生成对以检查顺序:
from itertools import tee, izip
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return izip(a, b)
def is_sorted(iterable, key=lambda a, b: a <= b):
return all(key(a, b) for a, b in pairwise(iterable))然后,您可以使用:
with open('potatoes.txt') as potatoes:
print is_sorted(potatoes)https://stackoverflow.com/questions/31868824
复制相似问题