[英]Function to return True if integer k and n in list?
Very new to python... If I give a list that has two integers n and k, the function should return Boolean True.对 python 非常陌生...如果我给出一个包含两个整数 n 和 k 的列表,该函数应该返回布尔值 True。 K has to be in the list the number of n times. K 必须在列表中出现 n 次。 For example, if I call matchingValues([1, 2, 1, 4, 1, 1], 1, 4) should return True since 1 is in the list 4 times.例如,如果我调用 matchingValues([1, 2, 1, 4, 1, 1], 1, 4) 应该返回 True,因为 1 在列表中出现了 4 次。 I'm guessing I have to use the .count() option but not sure how to write it... Wish I could give more code but unfortunately I am very lost我猜我必须使用 .count() 选项但不知道如何编写它...希望我能提供更多代码但不幸的是我很迷茫
def matchingValues(aList,n,k):
Better than a solution involving len()
is to use the .count()
method for lists.比涉及len()
的解决方案更好的是对列表使用.count()
方法。 It takes an argument, and returns the number of times that argument appears in the list that it is called on.它接受一个参数,并返回该参数出现在调用它的列表中的次数。
What you want to do is define a variable which counts how many times n is in the list你想要做的是定义一个变量来计算 n 在列表中的次数
found = 0
and then, iterate over your list with a loop然后,循环遍历您的列表
for x in range(0, len(aList)):
if aList[x] == n:
found += 1
return(found == k)
This is, however, if you want to avoid using the count
function:但是,如果您想避免使用count
函数,请执行以下操作:
return(aList.count(n)==k)
Using the manual, hand-written loop will allow you to exit the loop as soon as you know there are k
n
s in the list, if you want the loop to work like that (however, I have not provided that code. I have only written exactly what count
does)使用说明书,手写循环将让你退出循环,只要你知道有k
n
S IN列表中,如果你希望循环这样的工作(但是,我还没有提供的代码。我有只写了count
作用)
If you want there to be AT LEAST k
n
s in aList
, this would work for you如果您希望aList
至少有k
n
s,这对您aList
found = 0
for x in range(0, len(aList)):
if aList[x] == n:
found += 1
if found == k:
return True
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.