正在检测字符串迭代器是否为空sp

2024-05-16 12:18:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一小段代码来检测最常出现的字符。但是,我一直无法检测值是否为空格。你知道吗

下面是我的代码:

text = "Hello World!"

## User lower() because case does not matter
setList = list(set(textList.lower()))

for s in setList:
    if s.isalpha() and s != " ":
        ## Do Something

    else:
        setList.remove(s)

问题是集合列表以以下值结尾:

[' ', 'e', 'd', 'h', 'l', 'o', 'r', 'w']
<>我尝试了多种方法来检测空白区域,没有运气,包括在原始字符串值上使用String()。isspace()将不起作用,因为它至少查找一个字符。你知道吗


Tags: 代码texthelloworldnot字符lowersetlist
3条回答

问题是,您在迭代列表时正在从列表中删除项。千万不要那样做。考虑一下这个案子

['!', ' ', 'e', 'd', 'h', 'l', 'o', 'r', 'w']

这就是setList在转换为集合和列表之后的样子。在第一次迭代中,将看到!,并且将从setList中删除它。现在!被删除,下一个字符变成当前字符,即. For the next iteration, the iterator is incremented and it points to e(因为空格是当前字符)。这就是为什么它仍然存在于输出中。你可以用这个程序检查这个

num_list = range(10)

for i in num_list:
    print i,
    if i % 2 == 1:
        num_list.remove(i)
        pass

输出

0 1 3 5 7 9

但是如果您注释num_list.remove(i),输出将变成

0 1 2 3 4 5 6 7 8 9

为了解决实际问题,可以使用^{}来查找字符的频率,如下所示

from collections import Counter
d = Counter(text.lower())
if " " in d: del d[" "]      # Remove the count of space char
print d.most_common()

输出

[('l', 3), ('o', 2), ('!', 1), ('e', 1), ('d', 1), ('h', 1), ('r', 1), ('w', 1)]

一个简单的方法是首先从文本中删除空格

>>> text = "Hello world!"
>>> text = text.translate(None, " ")
>>> max(text, key=text.count)
'l'

但这并不是很有效,因为count会为每个字符扫描整个字符串一次(O(n2

对于较长的字符串,最好使用Collections.CounterCollections.defaultdict在单个过程中进行计数

如何在开始列表和集合之前移除空白空间:

text = "Hello world!"
text = re.sub(' ', '', text)

# text = "Helloworld!"

相关问题 更多 >