计算字符串中字符出现次数的最佳方法
您好,我正在尝试将这些 python 行写在一行中,但由于代码正在执行的字典修改而出现一些错误。
for i in range(len(string)):
if string[i] in dict:
dict[string[i]] += 1
我相信的一般语法是
abc = [i for i in len(x) if x[i] in array]
有人可以告诉我这如何工作考虑到我将 1 添加到字典中的值
谢谢
Hello I am trying to write these python lines in a single line but getting some errors due to the dictionary modifications the code is doing.
for i in range(len(string)):
if string[i] in dict:
dict[string[i]] += 1
the general syntax I believe is
abc = [i for i in len(x) if x[i] in array]
Would it be possible for someone to tell me how this might work considering that I am adding 1 to the value in a dictionary
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您想要做的事情可以使用
dict
、生成器表达式 和str.count()
:替代使用
set(string)
(摘自下面soulcheck
的评论):时机
看到下面的评论,我在这个答案和其他答案中进行了一些测试。 (使用 python-3.2)
测试功能:
测试执行:
测试结果:
What you're trying to do can be done with
dict
, a generator expression andstr.count()
:Alternative using
set(string)
(from a comment down below bysoulcheck
):Timing
Seen the comments down below I performed a little testing among this and other answers. (with python-3.2)
Test functions:
Test execution:
Test results:
Python 2.7+ 的替代方案:
输出:
Alternative for Python 2.7+:
Output:
这是集合模块的工作:
选项 1.- 集合。 defaultdict:
那么你的循环就变成:
选项2.- collections.Counter (来自 Felix 评论):
对于这种特定情况更好的替代方案,并且来自相同的
collections
模块:那么你只需要(!!!):
计数器仅在 python 2.7 中可用。所以对于 python < 2.7 你应该继续使用defaultdict
This is a job for the collections module:
Option 1.- collections. defaultdict:
then your loop becomes:
Option 2.- collections.Counter (From Felix comment):
An alternative that is better for this specific case, and from the same
collections
module:then you only need (!!!):
Counter is only available from python 2.7. So for python < 2.7 you should stay with defaultdict
这不是列表理解的良好候选者。您通常希望使用列表推导式来创建列表,并且其中产生副作用(更改全局状态)并不是一个好主意。
另一方面,你的代码可能会更好,像这样:
或者如果你真的想获得功能(我已将
dict
重命名为d
因为我需要 python 的内置 -在dict
函数中):请注意我如何没有在列表理解中更改
d
,而是在外部更新了d
它的。That's not a good candidate for a list comprehension. You usually want to use list comprehensions to make list, and to have side-effects (changing global states) in them is not such a good idea.
One the other hand, your code might be better off like this:
Or if you really want to get functional (I've renamed
dict
tod
because I need python's built-indict
function):Notice how I did not change
d
within the list comprehension, but instead updatedd
outside of it.你原来的循环完全不符合 Python 风格。如果您只想迭代
string
中的字母,则无需迭代range(len(string))
。改为这样做:Your original loop is hopelessly unPythonic. There's no need to iterate through
range(len(string))
if all you want is to iterate through the letters instring
. Do this instead: