簡體   English   中英

用索引比較兩個列表

[英]Compare two lists with index

我必須寫一個 boolean function 作為參數兩個相同字符串的列表( L1L2 )。

L1是男性名字列表, L2是相同長度的女性名字列表。 L1[k]L2 [k]一個禮物。

如果兩個人互相交換禮物,這個 function 應該返回 True,例如:

>>> compare(['A','B','C','D','E'],['C','D','A','E','B'])
True
>>> compare(['A','B','C','D','E'],['B','C','D','E','A'])
False

我必須使用列表索引。

我寫了一個 function 來獲取索引,但我完全不知道如何比較這兩個列表......

def index(name,L):
    i = 0
    for lookup in L:
        if lookup == name: return i
        i += 1

謝謝!

制作一個查找給予者 - > 接受者的字典更容易(也許更有效)。 然后你可以用它來確定給予是否對稱:

def compare(l1, l2):
    d = dict(zip(l1, l2))
    return any(l == d[d[l]] for l in l1)
    
compare(['A','B','C','D','E'],['C','D','A','E','B'])
# True

compare(['A','B','C','D','E'],['B','C','D','E','A'])
# False

如果你想測試all的給予是否是對稱的,你可以使用all()而不是any()

list1 = ['A','B','C','D','E'] # 1
list2 = ['C','D','A','E','B']`
compared_names = [] # 2

for i in range(len(list1)): # 3
    for j in range(len(list2)): # 4
        if list1[i] == list2[j]: # 5
        compared_names.append(list2[j])
if list1 == compared_names: # 6
    print('True, the lists are equal')
    print('This is the compared_names List: ' + str(compared_names))
else: # 7
    print('False, the lists are not equal')
    print('This is the compared_names list is: ' + str(compared_names))
  1. 前 2 個列表將相互比較
  2. compare_names 列表將存儲列表中的相似項目
  3. for 循環使用變量 mn 循環遍歷 list1 你必須獲取列表的長度,這樣當索引 i 插入第一個 if 語句時,它是一個數字而不是字符串,即 for i in list1 將返回字符'A','B'......所以你無法比較。 使用 range(len()) 將提供列表的索引 (0, 1,...) 而不是 char ('A', 'B'...)
  4. for list1 for 循環的所有內容都適用於 list2 循環。 此外,當 list1 循環運行時,它將進入索引零,然后 female_names 循環將運行它的過程(即 0 到 4)。 每次循環遍歷索引時,它都會檢查 if 語句。
  5. if 語句將插入每個循環的當前索引,因此對於 list1[0] == list2[1] 周圍的第一個循環。 由於 'A',= 'C' 它不會 append 'C' 到比較列表。 並且新循環將 go 到下一個索引以進行下一個循環。
  6. 一旦兩個列表都通過 if 語句循環比較 list1 和 compare_names 列表。 如果它們匹配,則 True 和 compare_list 將打印出來。
  7. 如果 list1 和 compatible_names 不匹配 False 並且 compare_list 將打印出來。

您可以將其轉換為 function ,例如 def compare(1, 2): ... 並將打印結果轉換為返回值。

def compare(A,B):
    for i in range(len(A)):
        if B[A.index(B[i])]==A[i]:
            return True
        print(B[A.index(B[i])],A[i]) # print to understand more
    return False

筆記

如果兩個列表沒有相似的字母,這將不起作用,因為它指的是字母。

暫無
暫無

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

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