简体   繁体   English

Python 2.7计算字符串数

[英]Python 2.7 counting number of strings

I'm trying to count the number of times in a list a string has more than 20 characters. 我试图计算一个字符串中超过20个字符的列表中的次数。

I am trying to use the count method and this is what I keep getting: 我正在尝试使用count方法,这就是我一直得到的:

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

edit: sorry for the indentation mistake before 编辑:抱歉缩进错误之前

Think you mean this, 以为你是这个意思,

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


>>> cnt
2

or 要么

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

or 要么

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

In this case, 在这种情况下,

x = len(line) > 20

x is a boolean, which cannot be "counted" in a string. x是一个布尔值,不能在字符串中“计数”。

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

You need to actually have a string or similar type (Unicode, etc.) to be counted in the line. 您实际上需要在该行中计算一个字符串或类似类型(Unicode等)。

I'd recommend using a simple counter for your purpose: 我建议您使用一个简单的计数器:

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

here, x is a boolean type ( True or False in Python), because len(line) > 20 is a logic expression. 此处, x是布尔类型(在Python中为TrueFalse ),因为len(line) > 20是逻辑表达式。

You may figure out the problem by debugging: 您可以通过调试找出问题所在:

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

Besides, x = len(line) > 20 is not a condition expression. 此外, x = len(line) > 20不是条件表达式。 You need to use if expression: 您需要使用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