python中请将字符串‘this is string’的每一个单词取出分别放入列表、字典(单词 序号:单词内容)
时间: 2024-04-13 15:28:24 浏览: 20
好的,我可以帮你解决这个问题。请看下面的代码:
```python
sentence = 'this is string'
words_list = sentence.split()
words_dict = {i+1: word for i, word in enumerate(words_list)}
print("单词列表:", words_list)
print("单词字典:", words_dict)
```
输出结果:
```
单词列表: ['this', 'is', 'string']
单词字典: {1: 'this', 2: 'is', 3: 'string'}
```
以上代码将字符串按空格进行分割,得到一个单词列表。然后使用字典推导式,将每个单词与其对应的序号存储在字典中。最后打印出单词列表和单词字典的内容。
相关问题
用Python编写代码,统计字符串中出现的每个单词出现次数并输出成字典
好的,以下是Python代码实现:
```python
str = "hello world hello"
words = str.split()
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts)
```
输出结果如下:
```
{'hello': 2, 'world': 1}
```
其中,words是将字符串按空格分割得到的单词列表,counts是一个字典,键为字符串中出现的每个单词,值为该单词出现的次数。
python已知一个字符串中存放了若干用空格分隔的单词,统计每个单词出现的次数。
可以使用Python中的字典来实现单词计数。具体步骤如下:
1. 将字符串按照空格分割成单词列表。
2. 遍历单词列表,对于每个单词,如果该单词已经在字典中,将该单词计数加1,否则将该单词添加到字典中,并将其计数初始化为1。
3. 最后遍历字典,输出每个单词及其对应的计数。
下面是使用Python实现的代码示例:
```python
string = "hello world hello python world"
word_list = string.split()
word_count = {}
for word in word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for word, count in word_count.items():
print(word, count)
```
输出结果:
```
hello 2
world 2
python 1
```