簡體   English   中英

Python,函數,這是怎么回事? 如果 lst1[index] != lst2[len(lst2) - 1 - index]

[英]Python, functions, what is going on here? if lst1[index] != lst2[len(lst2) - 1 - index]

有人可以幫我理解第 3 行嗎?

def reversed_list(lst1, lst2):
  for index in range(len(lst1)):
    if lst1[index] != lst2[len(lst2) - 1 - index]:
      return False
  return True

謝謝

function reversed_list正在做的是測試lst1是否是lst2的反轉版本(倒數也是如此)。

讓我們想象一下lst1是:

lst1 = [0, 1, 2, 3]

如果lst2lst1的反轉版本,則lst2必須按順序包含 function 的以下值返回 true:

lst2 = [3, 2, 1, 0]

在此示例中, len(lst1)等於4並且len(lst2)也等於4 ,因此if條件正在驗證,在第一次迭代中,如果值lst1[0 (index) ]等於lst2[ 4 (len(lst2)) - 1 - 0 (索引) ]

請注意,如果lst2如下所示,則 function reversed_list也將返回 true:

lst2 = [20, 15, 10, 5, 3, 2, 1, 0]

它的意思是:

  1. lst1[index] = lst1 的當前元素。 使用當前循環索引檢索。
  2. lst2[len(lst2) - 1 - index] = lst2 的元素,即lst2的長度減去 1 和當前循環索引。

總的來說,這意味着它檢查lst1的當前循環元素是否不等於 index 處的元素,該元素通過lst2的長度減去 1 和循環的當前索引來檢索。

  • lst1[index]正在檢查索引 position 的元素,索引從 0 開始。
  • lst2[len(lst2) - 1 - index]正在檢查lst2last-1 position 並從最后一個減去當前索引 position。

即,如果您檢查迭代,那么您將有一個清晰的想法。 我在下面傳遞兩個列表

list_1 = [1, 2, 3, 4, 5, 6, 7]
list_2 = [1, 2, 3, 4, 5, 6, 7]

現在檢查以下代碼的迭代

def reversed_list(lst1, lst2):
    for index in range(len(lst1)):
        print(lst1[index], lst2[len(lst2) - 1 - index])
        # if lst1[index] != lst2[len(lst2) - 1 - index]:
        #     return False
    return True


list_1 = [1, 2, 3, 4, 5, 6, 7]
list_2 = [1, 2, 3, 4, 5, 6, 7]

print(reversed_list(list_1, list_2))

檢查 output 的lst1[index], lst2[len(lst2) - 1 - index]

1 7
2 6
3 5
4 4
5 3
6 2
7 1

第一個列表從第 0 個 position 開始,最后一個列表從最后一個 position 開始。 現在申請你的條件希望你會做出一個好主意。

暫無
暫無

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

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