「python」setの要素を操作(add、clear、copy、difference等)する方法

1.add()
name = set(['Tom’,’Lucy’,’Ben’])
name.add('Juny’)
print(name)

出力結果:{'Lucy’, 'Juny’, 'Ben’, 'Tom’}

2.clear()
name = set(['Tom’,’Lucy’,’Ben’])
name.clear()
print(name)

出力結果:set()

3.copy()
name = set(['Tom’,’Lucy’,’Ben’])
new_name = name.copy()
print(new_name)

出力結果:{'Tom’, 'Lucy’, 'Ben’}

4.difference()
A = set([2,3,4,5])
B = set([3,4])
C = set([2])
n = n1.difference(n2,n3)
print(n)
出力結果:{5}

 

difference_update()
A = set([2,3,4,5])
B = set([4,5])
A.difference_update(B)
print(A)

出力結果:{2, 3}

5.discard()
n = set([2,3,4])
n.discard(3)
print(n)

出力結果:{2, 4}

6.intersection()
n1 = set([2,3,4,5])
n2 = set([4,5,6,7])
n = n1.intersection(n2)
print(n)

出力結果:{4, 5}

7.intersection_update()
n1 = set([2,3,4,5])
n2 = set([4,5,6,7])
n1.intersection_update(n2)
print(n1)

出力結果:{4, 5}

8.isdisjoint()
n1 = set([2,3,4,5])
n2 = set([4,5,6,7])
print(n1.isdisjoint(n2))

出力結果:False

9.issubset()
A = set([2,3])
B = set([2,3,4,5])
print(A.issubset(B))

出力結果:True

 

issuperset()
A = set([2,3])
B = set([2,3,4,5])
print(B.issuperset(A))

# 出力結果:True

 

10.pop()
n = set([2,3,4,5])
n1 = n.pop()
print(n,n1)

# 出力結果:{3, 4, 5} 2

11.remove()
n = set([2,3,4,5])
n.remove(2)
print(n)

# 出力結果:{3, 4, 5}

 

12.symmetric_difference()
A = set([2,3,4,5])
B = set([4,5,6,7])
print(A.symmetric_difference(B))

# 出力結果:{2, 3, 6, 7}

13.symmetric_difference_update()

A = set([2,3,4,5])
B = set([4,5,6,7])
A.symmetric_difference_update(B)
print(A)

# 出力結果:{2, 3, 6, 7}

14.union()

A = set([2,3,4,5])
B = set([4,5,6,7])
print(A.union(B))

# 出力結果:{2, 3, 4, 5, 6, 7}

15.update()
A = set([2,3,4,5])
B = set([4,5,6,7])
A.update(B)
print(A)

# 出力結果:{2, 3, 4, 5, 6, 7}

Python

Posted by arkgame