簡體   English   中英

Python列表理解失敗,並出現語法錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM