【问题标题】:Check if a word is between two other words, by alphabetical order按字母顺序检查一个词是否在其他两个词之间
【发布时间】:2018-07-08 15:44:48
【问题描述】:

我想按字母(或“字典”)顺序检查给定单词是否位于其他两个单词之间。

例如:

word1 = 'feelgoodlab'
word2 = 'elainedilley'
check = 'feelingfat'

我想看看check 是否介于word1word2 之间(是)。

我试过了:

word1 = 'feelgoodlab'
word2 = 'elainedilley'
check = 'feelingfat'

print(check >= word1 and check <= word2)

但这给了我False

【问题讨论】:

  • 这里正好相反:check &gt;= word2 and check &lt;= word1.
  • 您在 word1 和 word2 之间进行检查的说法是不正确的,至少从字符串比较的工作原理来看是不正确的。

标签: python string alphabetical


【解决方案1】:

你在这里基本上检查是否:

word1 <= check <= word2

但在这里,情况正好相反:word2 较小,word1 较大,但是我们可以将这两种可能性结合起来:

word1 <= check <= word2 or word2 <= check <= word1

因此,无论word1word2 之间的顺序是什么,它都会检查check 是否介于两者之间“夹在中间”。

【讨论】:

  • 补充一下,这个方法叫做chained comparisons,在文档here中有详细说明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多