2014-08-28 33 views
0

我在做练习3从http://cscircles.cemc.uwaterloo.ca/15b-python-pushups/,我做了代码的工作,但想知道是否有可能在更少的行中做到这一点?这里是我的解决方案:Python列表的理解失败,语法错误

los = [] # short for list of strings 
while True: 
    s = input() 
    if s == '###': break 
    los += s.lower().split() # making a list of lower case words from the input  sentences 
test = [] 
for x in los: 
    test += str(los.count(x)) # made a new list of the frequency of each word 
a = test.index(max(test)) # variable a provides the location of them most frequent word 
print (los[a]) # we know the position of the most frequent string, so find it in los. 
# a is not needed but it looks neater 

所以这部分尤其是我不是很满意:

for x in los: 
     test += str(los.count(x)) 

我要重新写,如:

test += str(list.count(x)) for x in los 

但告诉我无效的语法..所有提示?

+0

使用http://codereview.stackexchange.com/这种类型的问题\ – 2014-08-28 08:31:37

+0

只是把这个后while循环:'打印(MAX(LOS, key = los.count))' – grc 2014-08-28 08:38:57

+0

@grc谢谢你的工作,但我不明白这条线是如何工作的(完全),你能解释一下吗? – MathsIsHard 2014-08-28 08:55:33

回答

1

我想你想的语法是:

# No need for test = [] 
    test = [str(list.count(x)) for x in los] 
+0

是的,这就是我一直在寻找的,非常感谢 – MathsIsHard 2014-08-28 08:56:06