2015-04-01 60 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

相关问题