一、DefaultDict Tutorial
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't , set it to what you want.
For example:
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
print(i)
This prints:
>>> ('python', ['awesome', 'language'])
>>> ('something-else', ['not relevant'])
二、Task
You wil be given 2 integers, n and m. There are n words, wich might repeat, in word group A. There are m words belonging to word group B. For each m words, check whether the word has appeared in group A or not. Print the indices of each occurrence of m in gorup A. If it does not appear, print -1.
Sample Input
5 2
a
a
b
a
b
a
b
5 2 : Group A size n = 5, group B size m = 2
Group A contains 'a', 'a', 'b', 'a', 'b'
Group B contains 'a', 'b'
Sample Output
1 2 4
3 5
Group B contains 'a' , 'b':
'a' appeared 3 times in Group A, in positions 1, 2 and 4.
'b' appeared 2 times in Group A, in positions 3 and 5.
In the sample problem, if 'c' also appeared in word group B, you wold print -1.
三、代码
from collections import defaultdict
# 读取 n 和 m
n, m = map(int, input().split())
# 创建 defaultdict 来存储每个单词在 A 中的位置
word_positions = defaultdict(list)
# 读取 A 组的单词并记录位置
for i in range(1, n + 1):
word = input().strip()
word_positions[word].append(i)
# 读取 B 组的单词并检查它们在 A 中的出现情况
for _ in range(m):
word = input().strip()
if word in word_positions:
# 如果单词在 A 中出现,打印其所有出现的位置
print(*word_positions[word], sep=' ')
else:
# 如果单词不在 A 中出现,打印 -1
print(-1)
四、解读
from collections import defaultdict
- 导入 collections 模块的 defalutdict 类
- defaultdict 是 dict 的一个子类,提供一个工厂函数,用于为字典中不存在的键生成默认值
n, m = map(int, input().split())
- 读取用户输入的两个整数 n 和 m , n是A组单词数量,m是B组单词数量
- input().split() 读取一行输入并按空格分割成一个字符串列表
- map(int, ...) 将字符串转换成整数
word_position = defaultdict(list)
- 创建 defaultdict 实例,默认为空列表[]
for i in range(1, n+1): word = input().strip() word_positions[word].append(i)
- 读取 A 组的 n 个单词,索引从1开始,存储在 word_position 字典中。
- input().strip() 读取一行输入并去除首尾空白字符
for _ in range(m): word = input().strip()
- 循环读取 B 组 m 个单词
if word in word_positions: # 如果单词在 A 中出现,打印其所有出现的位置 print(*word_positions[word], sep=' ') else: # 如果单词不在 A 中出现,打印 -1 print(-1)
- 检查 A 组中是否存在 用户输入的 B 组的单词
- 如存在,则打印该单词在A组中出现的所有位置
- 如果不存在,则打印 -1
五、DefaultDict 和 普通字典的区别
defaultdict 与普通字典的区别:
1、默认值:defaultdict 允许你为不存在的键提供一个默认值,而普通字典在访问不存在的键时会引发 KeyError 。
2、初始化:defaultdict 需要在创建时提供一个工厂函数,这个函数会在访问不存在的键时被调用,以生成默认值。普通字典在创建时不需要提供默认值。
如何使用 defaultdict:
在你提供的代码示例中,defaultdict 被用来创建一个默认值为空列表 [] 的字典。这意味着当你尝试向一个尚未存在的键添加元素时,defaultdict 会自动为该键创建一个空列表,而不需要事先检查键是否存在。
defaultdict:
from collections import defaultdict
u = defaultdict(list)
key_list = ['python', 'something-else', 'python']
value_list = ['awesome', 'not relevant', 'language']
i = 0
for i in range(len(key_list)):
key = key_list[i]
value = value_list[i]
u[key].append(value)
print(u)
普通字典:
from collections import defaultdict
g = {}
key = 'python'
g['python'] = ["awesome"]
g['something-else'] = "not relevant"
g['python'].append("language")
print(g)
from collections import defaultdict
f = {}
key_list = ['python', 'something-else', 'python']
value_list = ['awesome', 'not relevant', 'language']
i = 0
for i in range(len(key_list)):
key = key_list[i]
value = value_list[i]
if key in f:
f[key].append(value)
else:
f[key] = [value]
print(f)