关于Python邻接脊椎动物判断代码核心逻辑的疑问
代码逻辑疑问解析
def any_adjacent_vertebrates(animals, vertebrates): result = False new_list = [] for i in range(len(animals)): for j in range(len(vertebrates)): if animals[i] == vertebrates[j]: new_list.append(i) for i in range(len(new_list) - 1): if new_list[i] + 1 == new_list[i + 1]: result = True return result animals = ["butterfly", "fly", "whale", "parrot"] #note: vertebrates whale and parrot are next to each other in the above animals list vertebrates = ["hamster", "crocodile", "parrot", "whale"] print(any_adjacent_vertebrates(animals, vertebrates)) animals = ["human", "fly", "hamster"] #note: vertebrates human and hamster are *not* next to each other in the above animals list vertebrates = ["hamster", "human", "mouse"] print(any_adjacent_vertebrates(animals, vertebrates)) animals = ["human", "fly", "starfish", "octopus", "spider", "mouse", "deer"] #note: vertebrates mouse and deer are next to each other in the above animals list vertebrates = ["human", "deer", "whale", "mouse"] print(any_adjacent_vertebrates(animals, vertebrates))
我理解代码前半部分是筛选出animals列表中同时存在于vertebrates列表里的动物,但对后续逻辑有三个疑问,下面逐一解释:
疑问1:为何向new_list追加索引i而非元素animals[i]?
因为我们要判断这些符合条件的动物在原animals列表里的位置是否相邻,元素本身没法直接体现位置关系,而索引i就是元素在animals里的位置序号——只有用索引才能判断两个元素是不是紧挨着的(比如索引2和3就对应原列表里相邻的两个元素)。如果存元素的话,就算两个元素相同,也没法知道它们在原列表的位置,更别说判断相邻了。
疑问2:第二个for循环范围设为len(new_list)-1的原因?
第二个循环是要逐个对比new_list里相邻的两组元素(比如第1个和第2个、第2个和第3个……)。假设new_list长度是n,那相邻的元素对一共有n-1组(比如长度为3的列表,只有0&1、1&2两组)。如果循环范围设成len(new_list),当i取到最后一个索引时,i+1就会超出列表的索引范围,直接报错。所以循环范围要设成len(new_list)-1,这样i最大只能到倒数第二个索引,i+1刚好是最后一个索引,不会越界。
疑问3:new_list[i]+1 == new_list[i+1]判断逻辑的由来?
new_list里存的是符合条件的元素在animals中的索引,两个索引如果是连续的(比如前一个是2,后一个是3),就说明这两个元素在原animals列表里是紧挨着的(索引2的元素后面就是索引3的元素)。所以用new_list[i]+1 == new_list[i+1]来判断这两个索引对应的元素是否相邻,只要有一组满足这个条件,就说明存在相邻的脊椎动物,把result设为True。
内容的提问来源于stack exchange,提问作者Donald
相关产品推荐
相关产品推荐

