数组中有整数,每个整数都有奇数位数或偶数位数。
我的输出:遍历数组中的每个元素,如果单独打印数字的偶数或奇数-
1
1
预期输出:获取数组中偶数整数的总数-
2
exampl=[22,234,2463]
def findEven(f):
countz=0
LengthOfInt=len(str(f))
if(LengthOfInt%2)==0: #if it is even, add 1 to count
countz+=1
print(countz)
for i in exampl:
findEven(i)发布于 2020-12-25 08:27:55
exampl=[22,234,2463]
def findEven(f):
return len(str(f))%2==0
count=0
for i in exampl:
if findEven(i)==True:
count+=1
print(count)或
exampl=[22,234,2463]
def findEven(f):
count=0
for i in f:
if len(str(i))%2==0:
count+=1
return count
print(findEven(exampl))发布于 2020-12-25 08:28:30
设置:
exampl=[22,234,2463]解决方案:
l = [x for x in exampl if x%2 == 0]
len(l)答案:
l
Out[23]: [22, 234]
len(l)
Out[24]: 2解释:
我们将列表exampl中的所有数字都取下来,如果它们可以被2除,那么只要看到len() of l,就会给我们计数。
发布于 2020-12-25 08:30:08
这里要做的是,变量countz的作用域是在findEven函数中。每次函数运行时,它都会被设置为0。此外,每次有偶数数字时,print函数都会运行.
相反,您要做的是创建一个返回布尔值的函数--无论该数字是否有偶数位数。然后,您可以计算True或False值。
example = [22, 234, 2463]
def is_even(value):
length = len(str(value))
return length % 2 == 0
count = 0
for i in example:
if is_even(i):
count += 1
print(count)https://stackoverflow.com/questions/65446449
复制相似问题