有人能帮忙写个简单的按名字首字母排序python程序吗?
就是输入几个人的名字,按照姓的字母顺序排列,如果姓相同,就按名的字首字母排列,下面这个是范例:Howmanynamesdoyouwanttoenter?5Enternam...
就是输入几个人的名字,按照姓的字母顺序排列,如果姓相同,就按名的字首字母排列,下面这个是范例:
How many names do you want to enter? 5
Enter name #1: Bill Clinton
Enter name #2: Michael Jackson
Enter name #3: Tony Blair
Enter name #4: Janet Jackson
Enter name #5: Oprah Winfrey
The names in order are:
Blair, Tony
Clinton, Bill
Jackson, Janet
Jackson, Michael
Winfrey, Oprah 展开
How many names do you want to enter? 5
Enter name #1: Bill Clinton
Enter name #2: Michael Jackson
Enter name #3: Tony Blair
Enter name #4: Janet Jackson
Enter name #5: Oprah Winfrey
The names in order are:
Blair, Tony
Clinton, Bill
Jackson, Janet
Jackson, Michael
Winfrey, Oprah 展开
2个回答
展开全部
#--encoding:utf-8--
def sortName(list):
#保存名字和第一个字母的map
nameMap ={}
#保存第一个字母并稍后进行排序
nameList =[]
for i in list:
nameMap[i[0]] = i
nameList.append(i[0])
nameList.sort()
for i in nameList:
print(nameMap[i])
if __name__ == '__main__':
list = ['Michael jack','Bill Cliton','Tony']
sortName(list)
运行结果:
Bill Cliton
Michael jack
Tony
汗 ,还有第二个字母,没看清。。不过原理一样的,map中key保存两个字母,就行了
修改后
#--encoding:utf-8--
def sortName(list):
#保存名字和第一个字母的map
nameMap ={}
#保存第一个字母并稍后进行排序
nameList =[]
for i in list:
len = i.find(' ')
str = i[0]
if(len > 0):
str = i[0]+i[len+1]
print str
nameMap[str] = i
nameList.append(str)
nameList.sort()
for i in nameList:
print(nameMap[i])
if __name__ == '__main__':
list = ['Michael jack','Michael cack','Michael zack','Bill Cliton','Tony']
sortName(list)
结果:
Bill Cliton
Michael cack
Michael jack
Michael zack
Tony
def sortName(list):
#保存名字和第一个字母的map
nameMap ={}
#保存第一个字母并稍后进行排序
nameList =[]
for i in list:
nameMap[i[0]] = i
nameList.append(i[0])
nameList.sort()
for i in nameList:
print(nameMap[i])
if __name__ == '__main__':
list = ['Michael jack','Bill Cliton','Tony']
sortName(list)
运行结果:
Bill Cliton
Michael jack
Tony
汗 ,还有第二个字母,没看清。。不过原理一样的,map中key保存两个字母,就行了
修改后
#--encoding:utf-8--
def sortName(list):
#保存名字和第一个字母的map
nameMap ={}
#保存第一个字母并稍后进行排序
nameList =[]
for i in list:
len = i.find(' ')
str = i[0]
if(len > 0):
str = i[0]+i[len+1]
print str
nameMap[str] = i
nameList.append(str)
nameList.sort()
for i in nameList:
print(nameMap[i])
if __name__ == '__main__':
list = ['Michael jack','Michael cack','Michael zack','Bill Cliton','Tony']
sortName(list)
结果:
Bill Cliton
Michael cack
Michael jack
Michael zack
Tony
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询