![](/img/trans.png)
[英]how to check whether a list element is in another list but also at the same index
[英]Check if an element in one list has the same index as another element in another list
我正在用數字在python上制作策划游戲。 我在檢查元素是否放置在錯誤位置時遇到問題。
因此,基本上,如果計算機生成的代碼沒有重復項,但用戶在輸入中使用了一些重復項(例如:COMP:1 2 3 4和USER:1 2 2 3)。 我不能只檢查一個“ 2”的位置,而不能同時檢查兩個位置。 請幫忙。
碼:
def incorrect_place():
incorrect_place = 0
if len(set(user_code)) != 4: #There are duplicates in the user's input
for index, num in enumerate(set(user_code)):
#I don't know how to check it now
incorrect_place += 1
return incorrect_place
如果有人也找到了計算機選擇了副本的解決方案,而用戶也喜歡(COMP:1、2、2、3和USER:2、3、4、4),我會很喜歡
基於對Mastermind是什么的一點研究,以及OP中的函數返回整數的事實,我的猜測是,您希望將計算機生成的列表與相同大小的用戶生成的列表進行比較,並了解如何許多職位都有不同的價值。
例:
Computer: 1 2 3 4
User: 1 2 2 3
S S D D # S=Same, D=Different
所以上面的答案是2。
我提出以下建議:
def incorrect_places(comp_list, user_list):
return sum(1 if a != b else 0 for a, b in zip(comp_list, user_list))
這個怎么運作:
zip(comp_list, user_list)
給我們一個2元組的列表,將每個列表中的對應值與它們出現的位置配對。 對於上面的示例,我們將得到: [(1, 1), (2, 2), (3, 2), (4, 3)]
1 if a != b else 0 for a, b in that_list
1,否則1 if a != b else 0 for a, b in that_list
-如果該對中的每個數字相同,則返回1,否則返回0。因此,我們得到[0, 0, 1, 1]
1 if a != b else 0 for a, b in that_list
[0, 0, 1, 1]
最后,我們將所有這些sum
起來以獲得答案。 希望這可以幫助。
編輯:評論者指出,這與執行sum(a != b for a, b in zip(comp_list, user_list))
。 我更喜歡更長和更易讀的版本,但是它們的工作方式相同。 這種差異純粹是風格上的。 選擇您喜歡的版本。
閱讀“兩位煉金術士”的答案后,我理解了您的問題。 這是我的嘗試:
def list_differences(list_a, list_b):
# Subtract list_b from list_a, element by element. The subtraction
# will result in non-zero values for elements that were different.
return [bool(list_a[i]-list_b[i]) for i in range(len(list_a))].count(True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.