2015-04-01 20 views
0

我想要查找在這些句子中有多少個' '(空白),這些句子恰好是列表中的元素。因此,對於: ['this is a sentence', 'this is one more sentence'] 調用元素0將返回值3,調用元素1會返回值4.我真的無法找到空白以及遍歷每個元素以找到一個具有最高數量的空格。查找列表中每個元素中某個字符的個數

回答

3

在使用count

>>> lst = ['this is a sentence', 'this is one more sentence'] 
>>> [i.count(' ') for i in lst] 
[3, 4] 

其他方式的簡單羅列,coprehension包括使用map

>>> map(lambda x:x.count(' '),lst) 
[3, 4] 

如果你想有一個可調用(這是一個函數,通過您的列表作爲迭代你已經提到)它可以實現爲

>>> def countspace(x): 
...  return x.count(' ') 
... 

和作爲

>>> for i in lst: 
...  print countspace(i) 
... 
3 
4 

該執行可以利用使用下述re module作爲正則表達式由Grijesh

>>> import re 
>>> [len(re.findall(r"\s", i)) for i in lst] 
[3, 4] 

後編輯要解決

正如你說的,你還需要找到最大元素,你可以使用

>>> def getmax(lst): 
...  vals = [i.count(' ') for i in lst] 
...  maxel = lst[vals.index(max(vals))] 
...  return (vals,maxel) 

>>> vals = [i.count(' ') for i in lst] 
>>> lst[vals.index(max(vals))] 
'this is one more sentence' 

這可以作爲一個可調用的實現,並以此爲

>>> getmax(lst) 
([3, 4], 'this is one more sentence') 

發表評論編輯

>>> s = 'this is a sentence. this is one more sentence' 
>>> lst = s.split('. ') 
>>> [i.count(' ') for i in lst] 
[3, 4] 
1

您聲明「空白」,通常包含這些字符'\t\n\x0b\x0c\r '以及任何Unicode字符,例如, u'\ u3000'(IDEOGRAPHIC SPACE)。

正則表達式解決方案是更好的解決方案之一,因爲除了通常的ascii解碼器之外,它很容易支持任何unicode空白碼。只需使用re.findall()並設置re.UNICODE標誌:

import re 

def count_whitespace(s): 
    return len(re.findall(r'\s', s, re.UNICODE)) 

l = ['this is a sentence', 
    'this is one more sentence', 
    '', 
    u'\u3000\u2029 abcd\t\tefghi\0xb \n\r\nj k l\tm \n\n', 
    'nowhitespaceinthisstring'] 

for s in l: 
    print count_whitespace(s) 

輸出

 
3 
4 
0 
23 
0 

一個簡單的,非正則表達式,方式做,這是str.split()這自然分割上的任何空白字符並且是從字符串中刪除所有空格的有效方法。這也適用於Unicode的空格字符:

def count_whitespace(s): 
    return len(s) - len(''.join(s.split())) 

for s in l: 
    print count_whitespace(s) 

輸出

 
3 
4 
0 
23 
0 

最後,挑選出一句最空格字符:

>>> max((count_whitespace(s), s) for s in l)[1] 
u'\u3000\u2029 abcd\t\tefghi\x00xb \n\r\nj k l\tm \n\n' 
+0

也可以添加鏈接到模塊,使得OP可以學習 – 2015-04-01 16:07:15

+0

@BhargavRao:也許...'re'提到的唯一外部模塊和DOCO不難找到。我已經添加了對're.findall()'的引用,以防萬一:) – mhawke 2015-04-01 16:14:57

+0

好的兄弟!總是鏈接到文檔是我們可以提供的最佳幫助:) – 2015-04-01 16:17:27

1

您可以使用Counter。我不知道是否是時間suming比.count()

from collections import Counter 
lst = ['this is a sentence', 'this is one more sentence'] 
>>>[Counter(i)[' '] for i in lst] 
[3, 4] 
+0

你可以添加鏈接到模塊,以便OP可以學習 – 2015-04-01 16:07:18

+1

@BhargavRao更新:),我也是你的粉絲堆棧:) – itzMEonTV 2015-04-01 16:14:28

+0

哈哈,真的嗎?非常感謝。任何特定的原因? – 2015-04-01 16:17:57

相關問題