[英]Python list comprehension fails with syntax error
我正在从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
但这告诉我语法无效。任何提示吗?
我认为您想要的语法是:
# No need for test = []
test = [str(list.count(x)) for x in los]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.