所以我有这个代码,我正在尝试创建一个从姓氏到名字的字典。我已经用我原来的字典创建了两个列表:
person_to_friends = {
'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'],
'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'],
'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],
'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'],
'Alex Dunphy': ['Luke Dunphy'],
'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],
'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],
'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],
'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],
'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'],
'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']
}
family_dictionary = []
friends_dictionary = []
last_names = []
for person in person_to_friends:
family_dictionary.append(person)
for name in person_to_friends[person]:
friends_dictionary.append(name)
上面的代码给了我两个列表,我试图用它们来创建一个lastnames到firstnames字典,其中键是人的lastnames,值应该是拥有这个lastname的所有人的名字。我不知道如何从这里开始。你知道吗
你不需要创建两个单独的列表来解决你的问题。你可以用原稿来做这个。以下是您需要做的,按以下顺序:
这里,
person_to_friends
是您的输入。也可以使用collections.defaultdict
对象,而不是带有setdefault
的dict
。我用itertools.chain
压平你的字典。使剩下的过程更简单。你知道吗如前所述,这就是如何使用
defaultdict
来获得优势。你知道吗这恰好比
dict
+setdefault
更有效。你知道吗你可以试试这个
输出:
不导入任何内容:
输出:
如果字符串的格式为
<FirstName> <LastName>
或<FirstName> <Middle> <LastName>
,并且仅用空格分隔,则应该检查split function.相关问题 更多 >
编程相关推荐