我对python很新,只是一起编码而且我完全被难倒了。我似乎无法找到一个更加虚拟的简单解释,如何将用户输入的偶数的数量计入列表。欢迎任何建议或想法,非常感谢。
答案 0 :(得分:1)
试试这个:
def GetEvenCount(inputList):
return sum(1-n%2 for n in inputList)
答案 1 :(得分:0)
偶数总是可以被2整除,因此您可以使用modulus
(%)运算符来检查数组中的每个数字是否均匀。如果该数字是偶数,则可以递增计数器以获得偶数。每次遍历列表中的元素时都会这样做。
define evenCount
go through each number in the list
if the number is even (divisible by 2)
increment evenCount
以下是实际代码:
listSize = int(input("Enter the list size: "))
numbers = []
evenCount = 0
for i in range(listSize):
number = int(input("Enter a number: "))
numbers.append(number)
for number in numbers:
if number % 2 == 0:
evenCount = evenCount + 1
print(evenCount)
答案 2 :(得分:0)
以下是一个例子:
>>> l=list(map(int, input('enter space separated list elements: ').split()))
enter space separated list elements: 1 2 3 4 5 6
>>> l
[1, 2, 3, 4, 5, 6]
>>> print('Number of even elements: '+str(len(list(filter(lambda x:x%2==0, l)))))
Number of even elements: 3
>>>
答案 3 :(得分:0)
使用计数器计算具有0提醒除以2的输入:
numbers = list()
counter = 0
while(True):
data = input("Enter number ('E' for exit): ")
if data == 'E':
break
numbers.append(data)
if int(data)%2 ==0:
counter +=1
print (numbers)
print (counter)
如下工作:
>>>
==================== RESTART: C:/Windows/System32/test.py ====================
Enter number ('E' for exit): 1
Enter number ('E' for exit): 2
Enter number ('E' for exit): 3
Enter number ('E' for exit): 4
Enter number ('E' for exit): 5
Enter number ('E' for exit): 6
Enter number ('E' for exit): E
['1', '2', '3', '4', '5', '6']
3
>>>