Python 如何生成一个返回相同数量索引的函数
我想做一个基于数字的智囊团游戏。尝试找出一个函数,该函数将两个列表作为参数,如果列表中的索引相同,则应返回相同的索引量 希望你明白我的意思;PPython 如何生成一个返回相同数量索引的函数,python,python-3.x,list,Python,Python 3.x,List,我想做一个基于数字的智囊团游戏。尝试找出一个函数,该函数将两个列表作为参数,如果列表中的索引相同,则应返回相同的索引量 希望你明白我的意思;P generated_number_as_list = [1,1,1,1] guess_as_list = [1,2,1,2] correct = right_inrightplace(guess_as_list, generated_number_as_list) print(correct) output >> 2 您可以使用zip
generated_number_as_list = [1,1,1,1]
guess_as_list = [1,2,1,2]
correct = right_inrightplace(guess_as_list, generated_number_as_list)
print(correct)
output >> 2
您可以使用zip将值与相应的索引进行比较,然后求和True,该值将转换为1
print(sum(x==y for x,y in zip(generated_number_as_list, guess_as_list))) #2
我在函数之外写的。只需在函数中复制for循环,并返回ans值作为输出
generated_number_as_list = [1,1,1,1]
guess_as_list = [1,2,1,2]
ans = 0
for i in range(len(generated_number_as_list)):
if guess_as_list[i] == generated_number_as_list[i]:
ans = ans + 1
print(ans)
为了好玩,这里有一个使用递归的解决方案:
def right_inrightplace(a, b):
if len(a) == 0 or len(b) == 0:
return 0
current = 0
if a[0] == b[0]:
current = 1
return current+right_inrightplace(a[1:],b[1:])
您也可以尝试以下方法:
a=[1,1,1,1]
b=[1,2,1,2]
print(min(len([x for x in a if x in b]),len([x for x in b if x in a])))
您可以将
求和
和映射
与运算符一起使用。eq
:
def right_inrightplace(a, b):
return sum(map(eq, a, b))
或者不使用其他库:
def right_inrightplace(a, b):
return sum(x == y for x, y in zip(a, b))
问题是你还没有在正确的地方写
。也许先试着写,然后再来寻求帮助?我喜欢它使用递归。但是如果你想在一个可读性更好的地方写这一行(如果a[0]==b[0]或者0,那么current=1),我该怎么写呢;P