python基础-set函数与sort方法

2020-03-04  本文已影响0人  吱吱菌啦啦
已知两个list:
a = [9,1,3,5,7]
b = [1,3,4,6,8]

题目一:去重合并排序

思路:set函数取并集
答案一
a = [9,1,3,5,7]
b = [1,3,4,6,8]
c = list(set(a+b))
print(c)
结果
[1, 3, 4, 5, 6, 7, 8, 9]

答案二
a = [9,1,3,5,7]
b = [1,3,4,6,8]
c = list(set(a) | set(b))
print(c)
结果
[1, 3, 4, 5, 6, 7, 8, 9]

题目二:合并取重复的数

思路:set函数取交集
a = [9,1,3,5,7]
b = [1,3,4,6,8]
c = list(set(a) & set(b))
print(c)
结果
[1, 3]

题目三:去掉两个list里相同的数,合并后降序排列

思路:set函数取差集,调sort方法排序
a = [9,1,3,5,7]
b = [1,3,4,6,8]
c = list(set(a) - set(b))
c.sort(reverse=True)
print(c)
结果
[9, 7, 5]

题目四:去掉两个list里相同的数,合并后升序排列

思路:set函数取差集,调sort方法排序
a = [9,1,3,5,7]
b = [1,3,4,6,8]
c = list(set(a) - set(b))
c.sort()
print(c)
结果
[5, 7, 9]
上一篇下一篇

猜你喜欢

热点阅读