Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在列表理解中向for循环添加变量_Python_Loops_For Loop_Counter - Fatal编程技术网

Python 如何在列表理解中向for循环添加变量

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

我想添加一个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 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]