给定以下代码:
c = [['dog', 'Sg', 'Good'], ['cat', 'Pl', 'Okay'], ['dog', 'Pl', 'Bad'],
['dog', 'Sg', 'Good'], ['cat', 'Pl', 'Okay'], ['dog', 'Pl', 'Okay'],
['dog', 'Sg', 'Good'], ['cat', 'Sg', 'Good'], ['dog', 'Pl', 'Bad'],
['dog', 'Sg', 'Good'],['cat', 'Pl', 'Okay'], ['dog', 'Pl', 'Bad']]
c
sets
个单词
outer_keys = set()
inner_keys = set()
for x in c:
outer_keys.add(x[0])
inner_keys |= set(x[1:])
for loop
dict
Lemma = dict()
for i in outer_keys:
j_d = dict()
for j in inner_keys:
j_d[j] = 0
j_d[i] = 0 # this is the line I can't replicate with a comprehension
Lemma[i] = j_d
for loop
结果:{'dog': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0, 'dog': 0},
'cat': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0, 'cat': 0}}
dict comprehension
:dict
理解来复制for-loop
Lemma = {j: {i: 0 for i in inner_keys} for j in outer_keys}
注:dog
应在外dog
的value
内,对于cat
也是如此
dict comprehension
结果:{'dog': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0},
'cat': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0}}
dict comprehension
复制for-loop
的结果?
只要从你的内心世界创建一个新的
dict
您可以将
dict.fromkeys
与inner_keys | {j}
一起使用:相关问题 更多 >
编程相关推荐