Python 2.7 统计字符串个数

Python 2.7 counting number of strings

我正在尝试计算列表中字符串超过 20 个字符的次数。

我正在尝试使用计数方法,这是我不断得到的结果:

>>> for line in lines:
        x = len(line) > 20
        print line.count(x)

编辑:抱歉之前的缩进错误

我认为你是这个意思,

>>> s = ['sdgsdgdsgjhsdgjgsdjsdgjsd', 'ads', 'dashkahdkdahkadhaddaad']
>>> cnt = 0
>>> for i in s:
        if len(i) > 20:
            cnt += 1


>>> cnt
2

>>> sum(1 if len(i) > 20 else 0 for i in s)
2

>>> sum(len(i) > 20 for i in s)
2

在这种情况下,

x = len(line) > 20

x 是一个布尔值,在字符串中不能是 "counted"。

>>> 'a'.count(False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object

您实际上需要有一个字符串或类似类型(Unicode 等)才能计入该行。

我建议您使用一个简单的计数器:

count = 0
for line in lines:
    if len(line) > 20:
        count += 1
print count
>>> for line in lines:
...     x = len(line) > 20

这里,x是布尔类型(Python中的TrueFalse),因为len(line) > 20是逻辑表达式。

调试可能会发现问题:

>>> for line in lines:
...     x = len(line) > 20
...     print x

此外,x = len(line) > 20不是条件表达式。您需要使用 if 表达式:

>>> count = 0
>>> for line in lines:    
...     if len(line) > 20:
...         count += 1    
... 
>>> print count