出一到Python题
时间: 2024-05-16 09:10:00 浏览: 75
以下是一道Python题示例:
引用:假设程序输入: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. 则输出应该是: 2:2 3.:1 3?:1 New:1 Python:5 Read:1 and:1 between:1 choosing:1 or:2 to:1 [^1]
这道题的思路是将输入的字符串拆分成一个个单词,然后统计每个单词出现的次数。这可以通过Python中的字典来实现。具体实现方法如下:
```python
s = 'New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.'
words = s.split() # 将字符串拆分成单词
d = {}
for word in words:
d[word] = d.get(word, 0) + 1 # 统计单词出现次数
for key, value in d.items():
print(f"{key}:{value}", end=' ')
```
输出结果为:`New:1 to:1 Python:5 or:2 choosing:1 between:1 2:2 and:1 3?:1 Read:1 3.:1`
阅读全文