簡體   English   中英

從文本文件檢查字典順序python

[英]Checking lexicographic order python from text file

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

I like potatoes
Potatoes are good
Potatoes contain starch

我想測試每個句子是否按字典順序排列。

如果句子是我希望它輸出“這是按字典順序”

我不太確定該怎么辦。

一種方法是讀取文件,分割行,將行排序,然后檢查順序是否相同或不同。

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

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

print sorted(potato_lines) == potato_lines

該問題的答案向您展示了如何不進行分類檢查。

例如, 此答案提供了一種生成對以檢查訂單的巧妙方法:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM