Python列表理解失败,语法错误

时间:2014-08-28 08:29:44

标签: python python-3.x

我正在从http://cscircles.cemc.uwaterloo.ca/15b-python-pushups/进行练习3,我让代码工作但是想知道是否有可能用更少的行来做?这是我的解决方案:

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

但是它告诉我语法无效......有哪些提示?

1 个答案:

答案 0 :(得分:1)

我认为你想要的语法是:

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