python - 使用 Max 函数时 Set 和 List 有什么区别?

标签 python

假设我们有一个列表 列表 = [1,1,2,2,3,1] 下面这两行给出相同的输出,即重复次数最多的元素。它们之间有什么区别?第一个如何工作

max(set(list),key=list.count) -- output: 1
max(list,key=list.count) -- output: 1

最佳答案

max 函数迭代其第一个参数中的值,对于每个值,它调用 key 函数,在我们的例子中是 list.count (列表中出现的次数),最后返回产生最大结果的值。

第一次通话: 输入是一个集合:(1,2,3) list.count 调用对应的结果为:[3, 2, 1] max 返回 1,因为它产生了最大的结果 (3)。

第二次调用: 输入是一个列表:[1,1,2,2,3,1] list.count 调用对应的结果为:[3, 3, 2, 2, 1, 3] 同样,max 返回 1,因为它产生了最大的结果 (3)。

因此,不同之处在于,在第一次调用中 max 需要迭代的值较少,因此进行的 list.count 调用也较少。尽管如此,两种情况的结果是相同的,因为 list.count 调用是在同一个列表上完成的。

是的,不要将变量命名为 list

关于python - 使用 Max 函数时 Set 和 List 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245579/

相关文章:

python多线程等待所有线程完成

python - 将 Python 算法翻译成 C++ 时遇到困难

python - sqlalchemy.exc.ProgrammingError : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version

python - 在哪里可以找到在 Python shell 中加载的第一个文本并对其进行更改?

Python效率: is it better to create new variables and assign tasks to it rather than keep on using same variable?

Python 复杂的字典键

python - 名称和值 - Go 与 Python

python - Adaptive Threshold 参数混淆

python - to_datetime() 的奇怪行为

python - 如何将日期字符串转换为 DateTime 对象?