Python:利用集合构造出相同省份的学生名单。

现有一组同学绮梦,冷伊一,香凝,梓轩,零语,圣博;他们的生源地
分别为山东、山西、湖南、内蒙古,山东,山西.
(1)利用集合分别记录学生名单和生源地;
(2)利用集合构造出相同省份的学生名单。

我编写的代码:
student_name = ['绮梦','冷伊一','香凝','梓轩','零语','圣博']
student_name1 = set (student_name)
print (student_name1)
birthplace = ['山东','山西','湖南','内蒙古','山东','山西']
birthplace1 = set (birthplace)
print (birthplace1)
dictionary = dict(zip(student_name,birthplace))
print (dictionary)
for student_name,birthplace in dictionary.items():
dict.setdefault(birthplace,set()).add(student_name)
student = [ len(values) > 1]
printf(student)
需要达成的运行结果:

img


我当前运行的结果:

img

student_name = ['绮梦','冷伊一','香凝','梓轩','零语','圣博']
student_name1 = set (student_name)
print (student_name1)
birthplace = ['山东','山西','湖南','内蒙古','山东','山西']
birthplace1 = set (birthplace)
print (birthplace1)
dictionary = dict(zip(student_name,birthplace))
print (dictionary)
a = {}
for student_name,birthplace in dictionary.items():
    a.setdefault(birthplace,set()).add(student_name)
print(a)
student = [a[i] for i in a if len(a[i]) > 1]
print(student)
{'圣博', '绮梦', '梓轩', '零语', '香凝', '冷伊一'}
{'湖南', '山西', '内蒙古', '山东'}
{'绮梦': '山东', '冷伊一': '山西', '香凝': '湖南', '梓轩': '内蒙古', '零语': '山东', '圣博': '山西'}
{'山东': {'绮梦', '零语'}, '山西': {'圣博', '冷伊一'}, '湖南': {'香凝'}, '内蒙古': {'梓轩'}}
[{'绮梦', '零语'}, {'圣博', '冷伊一'}]
student_name = ['绮梦','冷伊一','香凝','梓轩','零语','圣博']
birthplace = ['山东','山西','湖南','内蒙古','山东','山西']

print(set(student_name))
print(set(birthplace))
print(dict(zip(student_name,birthplace)))

dct = {}
for k,v in zip(birthplace,student_name):
    dct[k] = set(dct.get(k))|{v} if dct.get(k) else {v} #遍历时已存在的做并集运算
print(dct)
print('具有相同生源地学生名单为:',[i for i in dct.values() if len(i)>1])