3

以下程序代码片段计算文本字符串的字符频率并写入字典中。字典将字符作为键,将频率作为值。

text = "asampletextstring"
char_count = {}
for char in text:
    if char_count.get(char):
        char_count[char] += 1
    else:
        char_count[char] = 1

我的问题是,是否可以将上述代码段重写为comprehension?

4

4 回答 4

4

这是可能的,但效率低下

text = "asampletextstring"

char_count = { char : text.count(char) for char in text }

print(char_count)

输出

{'s': 2, 'x': 1, 'p': 1, 'm': 1, 'e': 2, 'r': 1, 'n': 1, 'g': 1, 'a': 2, 'i': 1, 'l': 1, 't': 3}

您可以编写较短版本的代码:

char_count = {}
for char in text:
    char_count[char] = char_count.get(char, 0) + 1
于 2018-10-31T18:53:28.053 回答
1

可以set()在这里使用以避免遇到字符 2 次或更多次。

text = "asampletextstring"
dict1 = {ch: text.count(ch) for ch in set(text)}

print(dict1)
{'s': 2, 'r': 1, 'i': 1, 'n': 1, 'a': 2, 'e': 2, 'p': 1, 't': 3, 'x': 1, 'l': 1, 'g': 1, 'm': 1}
于 2018-10-31T19:17:13.830 回答
1

每次我使用字典推导、通过将输入转换为集合的字典推导和传统的 for 循环进行一些分析时,我都好奇地研究各种方法的性能并证明推导并不好。这是有道理的,为什么这里的理解很昂贵,因为每次.count()都迭代整个来计算单个的频率textchar

from timeit import timeit

print('Approach 1 without set compehrension: {}'.format(timeit ('{ch: text.count(ch) for ch in text}',setup='text = "asampletextstring"',number=1000000)))
print('Approach 2 with set compehrension: {}'.format(timeit ('{ch: text.count(ch) for ch in set(text)}',setup='text = "asampletextstring"',number=1000000)))
print('Approach 3 simple loops :{}'.format(timeit('for c in text:char_count[c] = char_count.get(c, 0) + 1',setup='text = "asampletextstring";char_count={};',number=1000000)))
print('Approach 4 Counter :{}'.format(timeit('Counter(text)',setup='text = "asampletextstring";from collections import Counter;',number=1000000)))

输出:

Approach 1 without set compehrension: 4.43441867505
Approach 2 with set compehrension: 3.98101747791
Approach 3 simple loops :2.60219633984
Approach 4 Counter :7.54261124884
于 2018-10-31T19:48:41.057 回答
0

重写 - 不是真的,我没有看到任何简单的方法。我到达的最好的需要额外的字典。

d = {}
{ c: d.get(c, 0)  for c in text if d.update( {c: d.get(c,0) + 1} ) or True}

一个人将能够在 Python 3.8 中获得单行,但是通过(ab)使用赋值表达式

于 2018-10-31T20:11:11.740 回答