首先获取用户输入的列表,然后对列表进行去重与排序
"""
首先获取用户输入的列表,然后对列表进行去重与排序
"""
print('please enter the elements of list, separate them by comma.')
string = input('please enter the elements: ')
string_deal = string.split(',')
answer = set() # 去重
for number in string_deal:
if number.isdigit(): # make it stronger
answer.add(number)
result = [] # 排序 or result = list()
for i in answer:
result.append(int(i))
print(sorted(result))
用到了集合的互异性,和列表的可排序性
*注意 string_deal = string.split(’,’) 的运用,将用逗号相连的字符转换成字符串
*注意把元素分别添加到集合和列表中去的方法
please enter the elements of list, separate them by comma.
please enter the elements: 3,2,2,1,7,6,5,9,3,1,2,2
[1, 2, 3, 5, 6, 7, 9]
·
·
增加难度:
排序要求:排序后的数字在前,排序后的字母在后
# 排序要求:排序后的数字在前,排序后的字母在后
"""
name: wzl
date: 2020/3/6
task: 首先获取用户输入的列表,然后对列表进行去重与排序
排序要求:排序后的数字在前,排序后的字母在后
"""
# my wrong edition
print('please enter the elements of list, separate them by comma.')
string = input('please enter the elements: ')
string_deal = string.split(',')
answer = set() # 去重
for ii in string_deal:
if ii.isdigit(): # make it stronger
answer.add(ii)
if ii.isalpha():
answer.add(ii)
result = [] # 排序 or result = list()
for i in answer:
result.append(i)
print(sorted(result))
这种方法的错误在于直接对字母与数字的混合一起排序,这样就会直接按照ASCII码排序,那么100由于开头数字是1则会被错误的排列到2的前面
please enter the elements of list, separate them by comma.
please enter the elements: 2,100,b,A,c,a,B,7,2,2,1
['1', '100', '2', '7', 'A', 'B', 'a', 'b', 'c']
所以为了改正这种错误,要把数字和字母分开排序,在将两个列表粘和,如下:
# right solution
print('please enter the elements of list, separate them by comma.')
string = input('please enter the elements: ')
string_deal = string.split(',')
answer = set() # 去重
for ii in string_deal:
if ii.isalnum(): # make it stronger
answer.add(ii)
result_num = [] # 排序 or result = list()
result_str = []
for i in answer:
if i.isdigit():
result_num.append(int(i))
else:
result_str.append(i)
#result_num.sort()
#result_str.sort()
print(sorted(result_num)+sorted(result_str)) # 两个列表粘和
这样才能得到正确的答案
please enter the elements of list, separate them by comma.
please enter the elements: 2,100,b,A,c,a,B,7,2,2,1
[1, 2, 7, 100, 'A', 'B', 'a', 'b', 'c']