#小练习 合并首字母相同的男孩、女孩姓名 分类: python 小练习 2013-04-25 17:26 281人阅读 评论(0) 收藏
#这是python基础教程中的例子
girls=[ 'alice' , 'bernice' ,'clarice']
boys=[ 'chris' , 'arnold' , 'bob']
letter={}
for i in girls:
letter.setdefault( i[0] , [ ]).append(i)
print letter # {'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}
print res
==========================================================================================
拓展1:boys 列表中多出一个‘david’ 元素
girls=[ 'alice' , 'bernice' ,'clarice']
boys=[ 'chris' , 'arnold' , 'bob','david']
letter={}
for i in girls:
letter.setdefault( i[0] , [ ]).append(i)
print letter
# letter {'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}
print [ b + "+" + g for b in boys for g in letter.get(b[0],'') ] #此处结尾是一个包含一个空字符的字符串。
# 结果:['chris+clarice', 'arnold+alice', 'bob+bernice', 'david+ ' ]
==========================================================================================
拓展2:boys 列表中包含多个以‘a'字母开头的元素,且含有一个girls中不存在的以某字母开头的元素girls = ['alice','bernice','clarice','allen', 'Kallen']
boys = ['chris','arnold','bob','bob2','David']
# {'a': ['alice', 'allen'], 'c': ['clarice'], 'b': ['bernice'], 'K': ['Kallen']}
letter = {}
for i in girls:
letter.setdefault(i[0],[ ]).append(i)
print letter
[letter.setdefault(b[0],[]).append(b) for b in boys]
print letter
print letter.values() # [ ['alice', 'allen', 'arnold'], ['clarice', 'chris'], ['bernice', 'bob', 'bob2'], ['Kallen'], ['David'] ]
最终版本:
版本一:
#coding:utf-8
#合并首字母相同的姓名,并以字典形式返回
girls=['bernice','clarice','Amazon','June','alice']
boys=['chris','arnold','bob','Davide']
#合并列表
stu=girls+boys
'''
如果两个列表中含有共同元素,则使用for循环变量,append元素
for i in boys:
if i not in girls:
girls.append(i)
'''
#定义返回的字典
d={}
def main():
for name in stu:
if name[0].lower() in d:
d[name[0].lower()]+='-'+name
else:
d[name[0].lower()]=name
print d #{'a': 'Amazon-alice-arnold', 'c': 'clarice-chris', 'b': 'bernice-bob', 'd': 'Davide', 'j': 'June'}
if __name__ == '__main__':
main()
版本二:
#字典的值以列表形式返回
#coding:utf-8
girls=['alice','bernice','clarice','Amazon','June']
boys=['chris','arnold','bob','Davide']
#合并列表
stu=girls+boys
d={}
def main():
for name in stu:
if name[0].lower() in d:
d[name[0].lower()].append(name)
else:
d[name[0].lower()]=[name]
print d # {'a': ['alice', 'Amazon', 'arnold'], 'c': ['clarice', 'chris'], 'b': ['bernice', 'bob'], 'd': ['Davide'], 'j': ['June']}
if __name__ == '__main__':
main()
版权声明:本文为博主原创文章,未经博主允许不得转载。