我只是在学习Python,找到了一些甚至不如Java8方便的地方,比如word count
一开始我认为它很容易实现,就像
>>> {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}
但实际上我发现它有点麻烦
>>> 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
...
但在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()));
或者
word2CountMap = new HashMap<>();
for (String word : strings) {
word2CountMap.compute(word, (k, v) -> v == null ? 1 : v + 1);
}
我想知道是否存在一些高级的Python用法dict
可以实现它更容易,我不知道?你知道吗
你应该看看
collections.Counter
下面是一种使用} 计算单词的更快方法。你知道吗
collections
模块中的^{如果您想要一个
dict
对象而不是Counter
类型的对象:虽然您可以使用
collections.Counter()
—我建议您使用它—但是您可以使用字典理解轻松完成您的要求—这是一个与Python习惯用法紧密相关的概念:你看,问题很少是一种编程语言的功能不如另一种。这似乎是因为当你学习一门新语言时,你还没有必要的经验去了解适合某些任务的特定语言特性,这里就是这样。你知道吗
然而,这并不是说所有的语言都是一样的。每种语言都有差异,每种语言都有不同的哲学和不同的习语。当学习一门新语言时,最好问“我可以用这种方式用Java做X。Python的惯用方法是什么?”而不是“我可以用这种方式在Java中使用X。在Python中,它没有那么方便。“
相关问题 更多 >
编程相关推荐