There is a programming language with only four operations and one variable X:
++X and X++ increments the value of the variable X by 1.
--X and X-- decrements the value of the variable X by 1.
Initially, the value of X is 0.
Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
sum是内置的求和函数,sum里面是一个生成器表达式,可以创建一个生成器,你的问题里面提到generator expression是对的,可以搜索这个关键词了解相关知识。
只要是可以迭代的对象,都可以用于推导,不一定是string构成的list才可以,比如(i % 2 for i in range(10))就会返回一个生成器对象。
问题中的('+' in s or -1 for s in operations)也是返回一个生成器对象,生成器中的每个元素是通过迭代operations中的元素s生成的(根据s中是否包含加号,这个元素的值为1或者-1),最后再对其进行求和得到结果。
搜索列表推导式,就是简单for循环operations,然后判断元素中是否包含‘+’,如果有“+”,就等于1,否则等于 -1, 最后通过sum()求和。
可以分成两步理解:
如果对你有帮助,请点一下采纳谢谢
sum
是python内置的求和函数,sum
本质上是一个生成器表达式,也就是generator expression
,如果你想了解相关知识的话,其实可以看python的官方文档。
题中的sum('+' in s or -1 for s in operations)
是对迭代后的1
,-1
求和。