【问题标题】:Checking lexicographic order python from text file从文本文件中检查字典顺序python
【发布时间】:2015-08-07 02:34:54
【问题描述】:

我有一个文本文件,其中包含:

I like potatoes
Potatoes are good
Potatoes contain starch

我想测试每个句子是否按字典顺序排列。

如果句子是,我希望它输出“This is in lexicographic order”

我不太确定该怎么做。

【问题讨论】:

  • 你有什么问题?
  • 不知道从哪里开始...例如如何将文本文件分成不同的行,然后分成单词以检查它们的顺序。

标签: python input lexicographic


【解决方案1】:

一种方法是读入文件,拆分行,按顺序排列,然后检查顺序是否相同。

这可能不是最有效的方法,但可以:

with open('potatoes.txt') as potatoes:
    potato_lines = potatoes.readlines()

print sorted(potato_lines) == potato_lines

this 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)

【讨论】:

  • 如何分隔每一行,以便每个单独的句子都有输出?
  • @UdonSenpai 这是一个不同的问题。通过在这里发表评论,您只是在问我,而不是整个 stackoverflow。你需要展示一些代码,并且在你的提问中更加清晰。展示你尝试过的东西并询问为什么它不起作用(如果它不起作用)。见how to ask
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2015-09-27
  • 2019-10-20
  • 2020-03-26
  • 2017-09-19
  • 2012-03-08
  • 1970-01-01
相关资源
最近更新 更多