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

Python列表理解失败,出现语法错误,python,python-3.x,Python,Python 3.x,我从开始做练习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:

我从开始做练习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

但它告诉我无效语法。有什么提示吗?

我想你想要的语法是:

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

使用这种类型的问题\只需将其放在while循环之后:
print(max(los,key=los.count))
@grc谢谢你的工作,但我不明白那行是如何工作的(一点也不明白),你能解释一下吗?@VimalKarsan函数获取一个列表(或其他iterable)并返回最大的元素。当指定键时,它返回具有最大键的元素。因此,在这种情况下,
max
los
中的每个项目调用
los.count()
,并返回计数最高的项目。@grc真棒,谢谢。