首页 > 解决方案 > 以下 Pyhon 代码打印了什么?

问题描述

animals = ['horse', 'Pig', 'dog', 'Owl', 'lion', 'Hare', 'baboon', 'Fish', 'tiger', 'Zebra', 'Cow', 'Mouse', 'quail', 'Elephant']

for animal in animals:

    if (animal >= 'M') and (animal <= 'Z'):

        print(animal)

问题一:

怎么理解 (animal >= 'M') and (animal <= 'Z')

问题2:

正确答案是Pig Owl Mouse,为什么Zebra在这种情况下不打印?

标签: pythonlistfor-looplexicographic

解决方案


就像 zvone 指出的那样,字符串按字母顺序进行比较,因此不打印 Zebra。

在这种情况下,字母顺序将是。

X Y Z Za 斑马


推荐阅读