我只是在研究Python,发现一些地方甚至不如Java8那么方便,例如字数
起初我认为它可能很容易实现
>>> {x : x**2 for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Run Code Online (Sandbox Code Playgroud)
但实际上我发现它有点麻烦
>>> sent3
['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']
>>> for w in sent3:
... if w in word_count:
... word_count[w] += 1
... else:
... word_count[w] = 1
...
Run Code Online (Sandbox Code Playgroud)
但是在Java8中实现它非常方便,
List<String> strings = asList("In", "the", "beginning", "God", "created", "the", "heaven", "and", "the", "earth");
Map<String, Long> word2CountMap = strings.stream().collect(groupingBy(s -> s, counting()));
Run Code Online (Sandbox Code Playgroud)
要么
word2CountMap = new HashMap<>();
for (String word : strings) {
word2CountMap.compute(word, (k, v) -> v == null ? 1 : v + 1);
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否存在一些Python的高级用法dict可以更容易地实现它,我不知道?
这是一种使用Counterfrom collectionsmodule 计算单词的更快方法.
>>> from collections import Counter
>>> sent3 = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']
>>> Counter(sent3)
Counter({'the': 3, 'In': 1, 'beginning': 1, 'God': 1, 'created': 1, 'heaven': 1, 'and': 1, 'earth': 1, '.': 1})
Run Code Online (Sandbox Code Playgroud)
如果你想要一个dict对象而不是Counter类型的对象:
>>> dict(Counter(sent3))
{'In': 1, 'the': 3, 'beginning': 1, 'God': 1, 'created': 1, 'heaven': 1, 'and': 1, 'earth': 1, '.': 1}
Run Code Online (Sandbox Code Playgroud)