繁体   English   中英

如何使用python计算一行中的列数

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM