你好,我正在尝试将这些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,这可能是如何实现的吗?
谢谢
你好,我正在尝试将这些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,这可能是如何实现的吗?
谢谢
dict
、生成器表达式和str.count()
来完成:abc = dict((c, string.count(c)) for c in string)
使用set(string)
的替代方法(根据下面 soulcheck
的评论):
abc = dict((c, string.count(c)) for c in set(string))
看到下面的评论,我进行了一些测试,包括此答案和其他答案。 (使用Python 3.2)
测试函数:
@time_me
def test_dict(string, iterations):
"""dict((c, string.count(c)) for c in string)"""
for i in range(iterations):
dict((c, string.count(c)) for c in string)
@time_me
def test_set(string, iterations):
"""dict((c, string.count(c)) for c in set(string))"""
for i in range(iterations):
dict((c, string.count(c)) for c in set(string))
@time_me
def test_counter(string, iterations):
"""Counter(string)"""
for i in range(iterations):
Counter(string)
@time_me
def test_for(string, iterations, d):
"""for loop from cha0site"""
for i in range(iterations):
for c in string:
if c in d:
d[c] += 1
@time_me
def test_default_dict(string, iterations):
"""defaultdict from joaquin"""
for i in range(iterations):
mydict = defaultdict(int)
for mychar in string:
mydict[mychar] += 1
测试执行:
d_ini = dict((c, 0) for c in string.ascii_letters)
words = ['hand', 'marvelous', 'supercalifragilisticexpialidocious']
for word in words:
print('-- {} --'.format(word))
test_dict(word, 100000)
test_set(word, 100000)
test_counter(word, 100000)
test_for(word, 100000, d_ini)
test_default_dict(word, 100000)
print()
print('-- {} --'.format('Pride and Prejudcie - Chapter 3 '))
test_dict(ch, 1000)
test_set(ch, 1000)
test_counter(ch, 1000)
test_for(ch, 1000, d_ini)
test_default_dict(ch, 1000)
测试结果:
-- hand --
389.091 ms - dict((c, string.count(c)) for c in string)
438.000 ms - dict((c, string.count(c)) for c in set(string))
867.069 ms - Counter(string)
100.204 ms - for loop from cha0site
241.070 ms - defaultdict from joaquin
-- marvelous --
654.826 ms - dict((c, string.count(c)) for c in string)
729.153 ms - dict((c, string.count(c)) for c in set(string))
1253.767 ms - Counter(string)
201.406 ms - for loop from cha0site
460.014 ms - defaultdict from joaquin
-- supercalifragilisticexpialidocious --
1900.594 ms - dict((c, string.count(c)) for c in string)
1104.942 ms - dict((c, string.count(c)) for c in set(string))
2513.745 ms - Counter(string)
703.506 ms - for loop from cha0site
935.503 ms - defaultdict from joaquin
# !!!: Do not compare this last result with the others because is timed
# with 1000 iterations instead of 100000
-- Pride and Prejudcie - Chapter 3 --
155315.108 ms - dict((c, string.count(c)) for c in string)
982.582 ms - dict((c, string.count(c)) for c in set(string))
4371.579 ms - Counter(string)
1609.623 ms - for loop from cha0site
1300.643 ms - defaultdict from joaquin
dict()
构造函数,第二种解决方案是字典推导式。 - soulcheckabc = dict((c, string.count(c)) for c in set(string))
- soulcheck这里需要使用collections模块:
选项1.- collections.defaultdict:
>>> from collections import defaultdict
>>> mydict = defaultdict(int)
>>> for mychar in mystring: mydict[mychar] += 1
选项2.-collections.Counter(来自Felix评论):
这是一个更适用于此特定情况的替代方案,它来自于相同的collections
模块:
>>> from collections import Counter
>>> mydict = Counter(mystring)
计数器只适用于Python 2.7及以上版本。因此,对于Python < 2.7,您应该使用defaultdict。
Python 2.7+的替代方案:
from collections import Counter
abc = Counter('asdfdffa')
print abc
print abc['a']
输出:
Counter({'f': 3, 'a': 2, 'd': 2, 's': 1})
2
这不是列表理解的好选择。通常情况下,你会使用列表理解来创建列表,而在其中具有副作用(改变全局状态)并不是一个好主意。
另一方面,你的代码可能更适合像这样:
for c in string:
if c in dict:
dict[c] += 1
或者如果你真的想要变得更加函数化(我将dict
重命名为d
,因为我需要Python内置的dict
函数):
d.update(dict([ (c, d[c]+1, ) for c in string ]))
d
,而是在外部更新了d
。d = {}; d.update(dict([ (c, d[c]+1, ) for c in 'fubar' ]))
会产生 KeyError: 'f'
。将 d[c]
更改为 d.get(c, 0)
可以避免 KeyError,但它仍然无法正常工作,因为在循环中未更新 d,所以 d[c]
永远不能大于 0,因此 所有计数都是 1。 - John Machindict
中有某些内容,所以我也这样做了。 - cha0site>>> def count(s):
global k
list =[]
for i in s:
k=0
if i not in list:
list.append(i)
for j in range(len(s)):
if i == s[j]:
k +=1
print 'count of char {0}:{1}'.format(i,k)
>>> count('masterofalgorithm')
count of char m:2
count of char a:2
count of char s:1
count of char t:2
count of char e:1
count of char r:2
count of char o:2
count of char f:1
count of char l:1
count of char g:1
count of char i:1
count of char h:1
>>>
range(len(string))
进行迭代。请改为以下方式:for c in my_string:
if c in my_dict:
my_dict[c] += 1
else: my_dict[c] = 1
或者在开头设置 defaultdict
。所有的计数都将为零。 - John Machin
dict
是什么。如果它是空的,那么没有字符会被计算。 - reclosedev