python实现两个线性表集合A和B的并集

#encoding = utf-8
"""
@version:??
@author: xq
@contact:[email protected]
@file: listTest.py
@time: 2017/10/9 20:27
"""

#将所有在线性表A中但不在线性表B中的数据元素插入到B中
def unionList(listA,listB):
    for item in listA:          #遍历A中的元素
        if item in listB:       #如果A中的元素在B中
            continue            #略过,进行下一个元素的比较
        else:
            listB.append(item)  #否则,将该元素添加到B中
    return listB                #返回最后的集合

#测试
def main():
    list1 = [1,2,5,6,4]
    list2 = [3,5,1,7,9]
    ListUnion = unionList(list1,list2)#将list1和list2求并
    print(ListUnion)
if __name__ == '__main__':
    main()

运行结果:

[3, 5, 1, 7, 9, 2, 6, 4]



你可能感兴趣的:(大话数据结构)