【发布时间】:2014-01-18 16:36:45
【问题描述】:
此代码应该在 O(n) 线性时间内找到列表的模式。我想把它变成一个列表理解,因为我正在自学 Python,并且正在努力提高我的列表理解技能。
这些内容很丰富,但并没有真正回答我的问题:
Convert nested loops and conditions to a list comprehension
`elif` in list comprehension conditionals
Nested list comprehension equivalent
我遇到的问题是嵌套 if 和 try/except。我确信这是一个简单的问题,所以初级 Python 程序员可能很快就会有答案。
def mode(L):
# your code here
d = {}; mode = 0; freq = 0
for j in L:
try:
d[j] += 1
if d[j] > freq:
mode = j; freq = d[j]
except(KeyError): d[j] = 1
return mode
请注意,L 参数是一个整数列表,如下所示:
L = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]
我在想这样的事情:
[try (d[j] += 1) if d[j] > freq (mode = j; freq = d[j]) except(KeyError): d[j] = 1 for j in L]
但我没有足够的胶带来修复语法与那个东西的关系有多糟糕。
【问题讨论】:
-
import this。阅读 1-7。这些是我从 Python 中学到的最好的教训。
标签: python python-2.7 try-catch list-comprehension conditional-statements