我正在研究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}
但实际上我发现它有点麻烦
>>> 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
的一些高级用法可以更容易地实现它,我不知道?
答案 0 :(得分:5)
以下是使用collections
模块Counter
计算单词的更快方法。
>>> 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})
如果你想要一个dict
对象而不是Counter
类型的对象:
>>> dict(Counter(sent3))
{'In': 1, 'the': 3, 'beginning': 1, 'God': 1, 'created': 1, 'heaven': 1, 'and': 1, 'earth': 1, '.': 1}
答案 1 :(得分:3)
虽然您可以使用collections.Counter()
- 我建议您使用它 - 您可以使用字典理解轻松完成您的要求 - 这一概念与Python习惯密切相关:
>>> sent3 = ['In',
... 'the',
... 'beginning',
... 'God',
... 'created',
... 'the',
... 'heaven',
... 'and',
... 'the',
... 'earth',
... '.']
>>> {word : sent3.count(word) for word in sent3}
{'.': 1,
'God': 1,
'In': 1,
'and': 1,
'beginning': 1,
'created': 1,
'earth': 1,
'heaven': 1,
'the': 3}
>>>
你知道,问题很少是一种编程语言的功能不如另一种编程语言。这似乎就是这样,因为在学习一门新语言时,你还没有必要的经验来了解适合某些任务的特定语言特征,就像这里的情况一样。
但是,并不是说所有语言都是一样的。每种语言都有差异,每种语言都有不同的哲学和不同的习语。在学习一门新语言时,最好问一下&#34;我可以用Java做这样的X. Python中的惯用方法是什么?&#34; 而不是&#34;我可以用这种方式在Java中使用X.在Python中,它不那么方便。&#34;
答案 2 :(得分:0)
您应该查看collections.Counter
In [1]: from collections import Counter
In [2]: c = Counter(['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.'])
In [3]: c
Out[3]:
Counter({'.': 1,
'God': 1,
'In': 1,
'and': 1,
'beginning': 1,
'created': 1,
'earth': 1,
'heaven': 1,
'the': 3})