[英]How to count the number of columns in a line with python
我正在編寫一個python代碼,並試圖找出哪個函數最適合執行以下任務:
我想說:“如果一行中的單詞數不等於1,那就去做”
#Some code
words = line.split("\t")
if sum(words) != 1
#Do something
#Some code
words = line.split("\t")
if int(words) != 1
#Do something
#Some code
words = line.split("\t")
if len(words) != 1
#Do something
所有這些命令均返回以下錯誤:
File "test.py", line 10
if len(words) != 1
^
SyntaxError: invalid syntax
有人可以幫忙嗎?
之所以收到此錯誤,是因為在每個“ if”語句之后都缺少冒號。 另外,要獲取單詞中的元素數量,應使用len()而不是sum()。
這個
if sum(words) != 1
#Do something
應該是這樣的:
if len(words) != 1:
#Do something
if(len(line.split(" "))!=1) :
do something
您只需要檢查清單的長度即可:
if len(words) != 1:
#Do your stuff here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.