繁体   English   中英

Python 2.7计算字符串数

[英]Python 2.7 counting number of strings

我试图计算一个字符串中超过20个字符的列表中的次数。

我正在尝试使用count方法,这就是我一直得到的:

>>> 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是一个布尔值,不能在字符串中“计数”。

>>> '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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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