python - 如何计算列表末尾的出现次数

标签 python

我想在 python 中的列表末尾计算相同的出现次数。做起来非常简单,但我也对您的一些有趣的解决方案感兴趣。列表只能包含“1”或“2”项。结果必须在 [3,4,5] 中。小于 2 退出,大于 5 返回 5。

示例:

让我们拥有

  L = [1,1,2]
  Result: None (quit)

  L = [1,2,1,1]
  Result: None (quit)

  L = [1,2,1,1,1]
  Result: 3

  L = [1,1,2,2,2,2]
  Result: 4

  L = [1,2,1,1,1,1,1,1]
  Result: 5

最佳答案

喜剧一行答案:

def countOccurencesAtTheEndOfTheList(L):
    return (lambda num: None if num <= 2 else min(5, num))(len(L) if all(map(lambda x: x == L[-1], L)) else len(L) - 1 - [idx for idx, x in enumerate(L) if x != L[-1]][-1])

print countOccurencesAtTheEndOfTheList([1,1,2])
print countOccurencesAtTheEndOfTheList([1,2,1,1])
print countOccurencesAtTheEndOfTheList([1,2,1,1,1])
print countOccurencesAtTheEndOfTheList([1,1,2,2,2,2])
print countOccurencesAtTheEndOfTheList([1,2,1,1,1,1,1,1])

输出:

None
None
3
4
5

解释:

[idx for idx, x in enumerate(L) if x != L[-1]]获取 L 中与最后一个元素不匹配的每个元素的索引。
[idx for idx, x in enumerate(L) if x != L[-1]][-1]获取与最后一个元素不匹配的最右边元素的索引。这仅在列表中的所有元素都不相同时才有效。
len(L) - 1 - [the above line]如果列表中的所有元素都不相同,则获取列表末尾与最后一个元素匹配的元素数。
all(map(lambda x: x== L[-1], L)仅当列表中的所有元素都相同时才返回 True。
len(L) if [the above line] else [the line above the above line]获取列表末尾与最后一个元素匹配的元素数,无论列表中的所有元素是否相同。
lambda num: None if num <= 2 else min(5, num)返回 None如果该值太低,则将最大可能值限制为 5。

警告:仅供娱乐。请不要编写这样的代码。

关于python - 如何计算列表末尾的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14075397/

相关文章:

python - 等待请求完成 - Python Scrapy

python - 自扫码防止打印报表

Java 相当于 python 嵌套 for 循环

Python 时间复杂度(运行时)

python - 在 Sklearn 中留下一个

python - 如何在 Python/ElementTree 中输出 XML 声明 <?xml version ="1.0"?>

python - 如何在Python中为一个键存储多个值

python - 全局变量与局部变量的性能

python - Jupyter 中的 "ImportError: No module named ' jwt '"

python - 无法让 pyparsing Dict() 返回嵌套字典