简体   繁体   English

使用reduce()查找列表中最大值的变化次数(Python)

[英]Find how many times changes maximum value in a list with reduce() (Python)

Using reduce() function, I have to find how many times the maximum value of a list changes.使用reduce() function,我必须找出列表的最大值变化了多少次。 Here's my code, but I don't undestand why count remains to 0.这是我的代码,但我不明白为什么count保持为 0。

from functools import reduce

count = 0

heights = [10, 8, 11, 2, 1, 4, 13, 11]

reduce(lambda a, b: count + 1 if a < b else count + 0, heights, 0)

print(count)

The way reduce works is as follows: reduce的工作方式如下:

  • Take the default value (last parameter) and the first element of the sequence, and apply the provided function.取默认值(最后一个参数)和序列的第一个元素,并应用提供的 function。 Here, we take 0 and 10 , and compute: count + 1 if 0 < 10 else count + 0 .在这里,我们取010并计算: count + 1 if 0 < 10 else count + 0

  • Take the result from that operation, and apply the function to that and the second element, and so on.从该操作中获取结果,并将 function 应用于该元素和第二个元素,依此类推。

You can't expect to solve the problem this way, because none of this actually reassigns count - it stays equal to 0 no matter how many times this iterates.您不能指望以这种方式解决问题,因为这实际上都不会重新分配count - 无论迭代多少次,它都保持等于0 Each application of the lambda just produces either 0 or 1 . lambda的每个应用程序只产生01 Also, these 0 and 1 values are carried forward to the next step, instead of remembering the previous maximum value.此外,这些01的值会继续到下一步,而不是记住之前的最大值。

reduce is not the right tool for this job , but you can force it to work by computing a tuple of (maximum value seen so far, count) at each step. reduce不是这项工作的正确工具您可以通过在每一步计算一个 (迄今为止看到的最大值,计数) 的元组来强制它工作。 (You need to actually use the value returned by reduce , and not have any external count .) (您需要实际使用reduce返回的值,并且没有任何外部count 。)

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

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