已知两个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]
网友评论