![](/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.