Set
An unorder collection of a unquie object. No duplicate value.
不可以有重複的直,一般都是用在帳號上面。
Create set
1 | my_set= {1,2,3,4,5} |
output:
{1, 2, 3, 4, 5}
如果加重複會用最前面的
1 | my_set= {1,2,3,4,5,5} |
output:
{1, 2, 3, 4, 5}
adding set
1 | my_set= {1,2,3,4,5,5} |
output
‘{1, 2, 3, 4, 5, 100}`
上面會看到2
不會被加進去,因為他已經存在。
list to set
如果一把list不要重複,我們就要用到set ,會把重複的直移除。convert list to set, and remove duplicate value
1 | my_list= [1, 2, 3, 4, 5, 5, 100] |
output:
{1, 2, 3, 4, 5, 100}
basic method
- get value取直
set don’t support index,set 不支援 索引取直。
print(my_set[0])
# will be error
我們需要取直,就要把直放進去如:
1 | my_set= {1,2,3,4,5,5} |
len()
print(len(my_set))
#5convert to list
1
2my_set= {1,2,3,4,5,5}
print(list(my_set)) #[1, 2, 3, 4, 5]copy() and clear()
1
2
3
4
5my_set= {1,2,3,4,5,5}
new_set= my_set.copy()
my_set.clear()
print(my_set)
print(new_set)output:
set()
{1, 2, 3, 4, 5}
advance method
1 | my_set={1,2,3,4,5} |
difference() 只告訴你不同的,但會保留
print(my_set.difference(your_set)) #{1, 2, 3}
discard()
print(my_set.discard(5))
print(my_set)
output:
{1, 2, 3, 4}difference_update() 把相同的移除,只保留不同的。他會修改
my_set.difference_update(your_set)
print(my_set)
output:
#{1, 2, 3}intersection() something in common
print(my_set.intersection(your_set)) #{4, 5}
of shorthand
print(my_set & your_set) #{4, 5}
- isdisjoint() something not in common
print(my_set.isdisjoint(your_set)) #false
if we use like this:
1 | my_set={1,2,3} |
- union() 合併一樣的移除重複
print(my_set.union(your_set))
or shorthand
print(my_set| your_set)
output:
{1, 2, 3, 4, 5, 6, 7, 8, 9}`
issubset()
1
2
3my_set={4,5}
your_set={4,5,6,7,8,9,10}
print(my_set.issubset(your_set)) # truemy_set is a subset of your_set。my_set在your_set裡面,因此就會true
issuperset()
1
2
3
4my_set={4,5}
your_set={4,5,6,7,8,9,10}
print(your_set.issuperset(my_set)) # true
print(my_set.issubset(your_set)) # true