繁体   English   中英

用 Python 中的列表理解替换嵌套的 for 循环

[英]Replace nested for loop with list comprehension in Python

给定整数列表c ,我想执行以下操作:

  1. 计算c有多少元素小于索引i ,其中i0len(c) 例如: c=[1, 0, 2, 1] ,那么上面的 output 将是b=[1, 3, 4, 4]因为只有c的第1元素小于等于i=0 , then there are 3 elements of c less than or equal to i=1 , then there are 4 elements of c less than or equal to i=2 , and lastly there are 4 elements of c less than or equal to i=3 .

  2. a=[b[0] b[1]-1 b[2]-2... ]

  3. 查找math.prod(a)


我设法使用嵌套的 for 循环来做到这一点,但我正在学习列表推导并希望将它们转换为列表推导中的嵌套 for 循环。

#this code works
def solve(c):
    a=1
    for i in range(len(c)):
        a=a*(sum(element<=i for element in c)-i)
    return(a)
#input c=[1, 0, 2, 1]
#output 4

但是这个失败了:

$this code does not work
def solve(c):
    a=1
    return([(a=a*(sum(element<=i for element in c)-i)) for i in range(len(c))])

[[item for item in c if item <= ind] for ind in range(len(c))]为您提供索引 <= 的项目列表。

[len([item for item in c if item <= ind]) - ind for ind in range(len(c))]会给你第二点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM