【问题标题】:How to add a variable to a for loop in list comprehension如何在列表理解中将变量添加到 for 循环
【发布时间】:2020-11-24 05:34:38
【问题描述】:

我想添加一个计数变量来计算循环中的比较,但在列表理解中。

有什么想法吗?

contador_C = 0
c = [x for x in S if d<= x and x <= u (contador += 1)]                 

# this is what I'm trying to get but in a list comprehension way

# contador_C = 0
# for i in S:
#     if d<= i and i<= u:
#         contador_C += 1
#         c.append(i)

【问题讨论】:

  • 你为什么不在最后做contador_C = len(c)

标签: python loops for-loop counter


【解决方案1】:

最简单的替代方法,只需contador_C = len(c)

如果你必须这样做,你可以使用定义一个新函数来做到这一点,

contador_C = 0
def temp(ele):
    global contador_C
    contador_C += 1
    return ele
c = [temp(x) for x in S if d <= x and x <= u] # call the function with the element

【讨论】:

    【解决方案2】:

    有几种方法可以实现这一点。

    方法一:

    def filter_item(item):
        global contador_C, d, u
        if d <= item <= u:
            contador_C += 1
            return True
        else:
            return False
    
    c = filter(filter_item, S)
    

    方法二:

    def count_contador(item):
        global contador_C
    
        contador_C += 1
    
        return item
    
    c = [count_contador(item) for item in S if d <= item <= u]
    

    对于第一种情况,它返回生成器。

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 2021-02-18
      • 2021-11-11
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      相关资源
      最近更新 更多