#题目
#思路
先整体建立顺序表,删除B中与A相同的元素,再将A、B添加到新建列表中
请各位指教一下编程(python版)
def union_sets(a, b):
c = set(a) # 初始化集合C为集合A的元素
for element in b: # 遍历集合B的元素
if element not in c: # 如果元素不在集合C中,则将其添加到集合C中
c.add(element)
return sorted(list(c)) # 将集合C转为排序后的列表
A = [1, 3, 2]
B = [5, 1, 4, 2]
C = union_sets(A, B)
print(C)
【相关推荐】
list_A=[1,'aa',2,'bb',3,'cc',4,12,12]
list_B=[]
if len(list_A)>=5:
list_B = list_A[0:5]
print('列表B:',list_B)
else:
print('列表A不足5个元素')
结果:列表B: [1, 'aa', 2, 'bb', 3]