-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSets
More file actions
102 lines (77 loc) · 2.56 KB
/
Sets
File metadata and controls
102 lines (77 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
1.Sets!
(sets are like formal math sets)
#sets DO NOT have duplicate values -
#elements in sets aren't ordered
#you access items in a set by index --- NO ORDER!
2.create and access
{} (not a key: value) / set function
# can't use s[0]
s = set({1,2,3,4,5,5,5,6})
print(s) #{1, 2, 3, 4, 5, 6}
s2 = {1,4,5,5, 'a' 'b', 234.5, 7/5}
# 注意和dic区别是没有key:value pair
#注意上面的例子我在a,b之间忘记加 ,了,成为了一个合并的array
print(s2) #{1, 'ab', 1.4, 4, 5, 234.5}
print(type(s2)) #<class 'set'>
print(4 in s) #True
#还是可以loop through it
for stuff in s2:
print(stuff)
'''
注意顺序是乱的,且是已经完成计算的
1
1.4
4
ab
5
234.5
'''
print(len(s)) #6 -- give you the number of unique items
print(list(s)) # by this way you can convert a duplicate list to a de-dup list
# ---list(set(cities))
3.set methods
add() # add an element to a set, if the element is already in the set, the set doesn't change
s.add(7)
print(s) #{1, 2, 3, 4, 5, 6, 7}
s.add(1)
print(s) #{1, 2, 3, 4, 5, 6, 7}
#s.add(10,9) #TypeError: add() takes exactly one argument (2 given)
remove(): # removes a value from the set-- returns a KeyError if the value is not found
s.remove(7)
print(s) #{1, 2, 3, 4, 5, 6}
#s.remove(100) # KeyError: 100
#use .discard() to avoid KeyErrors
s.discard(6)
print(s) #{1, 2, 3, 4, 5} can also delete
s.discard(8)
print(s) #{1, 2, 3, 4, 5} no error reported
clear() : # remove all the contents of the set
another_s.clear()
print(another_s) #set()
print(type(another_s)) #<class 'set'>
4.copy() creates a copy of the set, a new one!
another_s = s.copy()
print(another_s) #{1, 2, 3, 4, 5}
print(another_s is s) #False
print(another_s == s) #True
5.set Math
#union -- pipe
print(math_students | biology_students) #{'Jane', 'Oliver', 'Matthew', 'Apa', 'Chard', 'Helen', 'Mesut', 'Pat', 'James'}
#intersection -- &
print(math_students & biology_students) #{'Matthew', 'James'}
6.set Comrehension --also return a set
print({ke ** 2 for ke in range(10)})
#{0, 1, 64, 4, 36, 9, 16, 49, 81, 25} check there is no order of it
# if there is : then it will be a dict
print({ke: ke ** 2 for ke in range(10)})
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
print({char.upper() for char in "hellor"})
#{'R', 'L', 'O', 'E', 'H'}
def are_all_vowels_in_string(string):
return len({char for char in string if char in "aeiou"}) ==5
string = "aeiouaaa"
string2 = "sequoia"
string3 = "saqw"
print( are_all_vowels_in_string(string)) #True
print( are_all_vowels_in_string(string2)) #True
print( are_all_vowels_in_string(string3)) #False