Python 如何在列表理解中向for循环添加变量
我想添加一个count变量来计算循环中但在列表理解中的比较 你知道怎么做吗Python 如何在列表理解中向for循环添加变量,python,loops,for-loop,counter,Python,Loops,For Loop,Counter,我想添加一个count变量来计算循环中但在列表理解中的比较 你知道怎么做吗 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
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\u C=0
c=[x代表S中的x如果d是最简单的替代方法,只需执行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
contador\u C=0
def温度(ele):
全球康塔多大学
contador_C+=1
返回元素
c=[temp(x)对于S中的x,如果d有几种方法可以实现这一点
方法1:
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过滤器项目(项目):
全球康塔多大学C、d、u
如果d,你为什么不在最后做contador\u C=len(C)
?
def count_contador(item):
global contador_C
contador_C += 1
return item
c = [count_contador(item) for item in S if d <= item <= u]