【发布时间】:2019-11-23 13:38:06
【问题描述】:
我必须设置两个循环。一个保持对列表中负数的总数并返回的值。另一个将否定附加到一个单独的列表也将被返回。我只能在每个循环中返回第一个值。
# Given the parameter list, returns the count of negative numbers in the list
def num_negatives(list):
negatives = 0
for neg in list:
if neg < 0:
negatives += 1
return negatives
# Given the parameter list, returns a list that contains only the negative numbers in the parameter list
def negatives(list):
negList = []
for negItems in list:
if negItems < 0:
negList.append(negItems)
return negList
# Prompts the user to enter a list of numbers and store them in a list
list = [float(x) for x in input('Enter some numbers separated by whitespace ').split()]
print()
# Output the number of negatives in the list
print('The number of negatives in the list is', num_negatives(list))
print()
# output the list of negatives numbers
print('The negatives in the list are ', end = '')
for items in negatives(list):
print(items, ' ', sep = '', end = '')
print('\n')
如果我在程序开始时输入值1 2 3 4 5 -6 7 -8 9 -12.7,我应该会收到这个。
The number of negatives in the list is 3
The negatives in the list are -6.0 -8.0 -12.7
相反,我只得到:
The number of negatives in the list is 1
The negatives in the list are -6.0
【问题讨论】:
标签: python list for-loop return negative-number