def comparing_numbers(number1,number2,number3,number4,number5, numbers(), correct_numbers):
if number1 == numbers():
correct_numbers = correct_numbers + 1
print("")
if number2 == numbers():
correct_numbers = correct_numbers + 1
print("")
if number3 == numbers():
correct_numbers = correct_numbers + 1
print("")
if number4 == numbers():
correct_numbers = correct_numbers + 1
print("")
if number5 == numbers():
correct_numbers = correct_numbers + 1
comparing_numbers(number1,number2,number3,number4,number5, numbers(), correct_numbers)
print(correct_numbers)
所以基本上我需要一些代码,让我的五个变量(number1,number2,number3,number4,number5)搜索一个名为(numbers())的数组,如果变量中的数字与任何数字匹配在数组中,它将一个加到我的变量(correct_numbers)。我需要它搜索五次(每个变量)
我试图制作一些代码来解释我所说的内容,但它无法正常工作
由于
答案 0 :(得分:0)
以下代码应该完成工作。
如果它出现在给定的列表(数组)中,它会检查数字中的每个数字,并返回找到的数字。
def findSimilars(n1, n2, n3, n4, n5, all):
correct_found = 0
# all is a list of numbers to check if the numbers are in
my_numbers = [n1,n2,n3,n4,n5] # make the numbers a list for simple iteration
for n in my_numbers: # go over each of the numbers
if n in all: # if the current number is in my_numbers
correct_found += 1
return correct_found
all_numbers = [0,1,2] # ... All the values you want to check if your numbers are there
correct_times_found = findSimilars(1,2,3,4,5,all_numbers) # An example for function call
print "Number of times found: %d" % (correct_times_found)
答案 1 :(得分:0)
您可以将您的号码存储为列表吗? 如果是这样的话:
numbersToCheck = [number1,number2,number3,number4,number5]
numbers = [1,2,3,4,5]
correct_numbers = len([num for num in numbers if num in numbersToCheck])
答案 2 :(得分:0)
您正在复制函数中的代码,该代码可能属于for循环。了解我们如何简化功能,并迭代您的数字列表:
def comparing_numbers(check_numbers, numbers(), correct_numbers):
for number in check_numbers:
if number in numbers():
correct_numbers += 1
return correct_numbers
check_numbers = [number1, number2, number3, number4, number5]
correct_numbers = 0
print(comparing_numbers(check_numbers, numbers(), correct_numbers)
答案 3 :(得分:0)
可能这就是你要做的事情
def comparing_numbers(number1,number2,number3,number4,number5, numbers):
correct_numbers = 0
for number in [number1,number2,number3,number4,number5]:
if number in numbers:
correct_numbers += 1
return correct_numbers
correct_numbers = comparing_numbers(number1,number2,number3,number4,number5, numbers)
print(correct_numbers)
答案 4 :(得分:-2)
in
语句会检查您的号码中是否包含该号码。
如果是,则将其添加到correct_numbers。
if number1 in numbers:
correct_numbers += 1
if number2 in numbers:
correct_numbers += 1
if number3 in numbers:
correct_numbers += 1
if number4 in numbers:
correct_numbers += 1
if number5 in numbers:
correct_numbers += 1