编程语言
首页 > 编程语言> > day14 Python集合关系运算交,差,并集

day14 Python集合关系运算交,差,并集

作者:互联网

low逼写法,没用集合

python_1 = ['charon','pluto','ran']
linux_1 = ['ran','xuexue','ting']

python_and_linux = []
for p_name in python_1:
    if p_name in linux_1:
        python_and_linux.append(p_name)
print(python_and_linux)

结果:
['ran']

 高级点写法用集合了

python_1 = ['charon','pluto','ran','charon']
linux_1 = ['ran','xuexue','ting']

p_s = set(python_1)
l_s = set(linux_1)
print(p_s,l_s)
#交集
print(p_s.intersection(l_s))
print(p_s&l_s)
#并集
print(p_s.union(l_s))
print(p_s|l_s)
#差集
print(p_s.difference(l_s))
print(p_s - l_s)
print(l_s.difference(p_s))
print(l_s - p_s)

结果:
{'charon', 'ran', 'pluto'} {'ting', 'xuexue', 'ran'}
{'ran'}
{'ran'}
{'ting', 'charon', 'xuexue', 'ran', 'pluto'}
{'ting', 'charon', 'xuexue', 'ran', 'pluto'}
{'charon', 'pluto'}
{'charon', 'pluto'}
{'ting', 'xuexue'}
{'ting', 'xuexue'}

 

标签:ting,并集,charon,Python,python,day14,ran,linux,print
来源: https://www.cnblogs.com/charon2/p/10356159.html