【问题标题】:How to make a for loop keep returning values?如何使 for 循环保持返回值?
【发布时间】: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


    【解决方案1】:

    我认为您正在搜索yield,这是创建可迭代对象的优雅解决方案。

    def num_negatives(list):
        negatives = 0
        for neg in list:
            if neg < 0:
                yield neg  # I return the negative number directly.
    
    def negatives(list): 
        negList = []   
        negatives_generator = num_negatives(list)
        for negItem in negatives_generator:
            negList.append(negItem)
        return negList 
    

    最后你可以打印否定列表和len(negatives),你现在都有了。

    更多详情:What does yield do?

    【讨论】:

    • 虽然这是一个有用的工具,但它并没有解决 OP 的情况,它似乎处理的是一个需要特定方法的作业问题。
    【解决方案2】:

    您的退货地点有误。您不想多次返回。您只想在函数运行完成后返回最终值一次。所以你的函数应该是这样的:

    # Find number of negative numbers in the list
    def num_negatives(list):
        negatives = 0
        for neg in list:
            if neg < 0:
                negatives += 1
        return negatives
    
    def negatives(list):    
        negList = []
        for negItems in list:
            if negItems < 0:
                negList.append(negItems)
        return negList       
    

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 1970-01-01
      • 2011-11-25
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2016-08-23
      相关资源
      最近更新 更多