簡體   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