[英]Compare two lists with index
我必須寫一個 boolean function 作為參數兩個相同字符串的列表( L1
和L2
)。
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))
您可以將其轉換為 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.