基本用法
char_list = ['a', 'b', 'b', 'c', 'c', 'd']
print(set(char_list))
sentence = 'Welcome Back to This Tutorial'
print(set(sentence))
输出
set(['a', 'c', 'b', 'd'])
set(['a', ' ', 'c', 'B', 'e', 'i', 'h', 'k', 'm', 'l', 'o', 's', 'r', 'u', 't', 'W', 'T'])
set中添加一个元素
char_list = [‘a’, ‘b’, ‘b’, ‘c’, ‘c’, ‘d’]
print(set(char_list))
unique_char = set(char_list)
unique_char.add(‘x’)
print(unique_char)set([‘a’, ‘c’, ‘b’, ‘d’])
set([‘a’, ‘x’, ‘c’, ‘b’, ‘d’])
从set中删除元素
- unique_char.clear() # 使用这种方式将直接清空set
- unique_char.remove(‘a’) # 使用这种方式,如果set中不含有要remove的元素,则程序会报错
- unique_char.discard(‘y’) # 使用这种方式删除元素,即使set中不含有要discard的元素,也不会报错,只会返回原字符串。
比较两个set的方法
char_list = [‘a’, ‘b’, ‘b’, ‘c’, ‘c’, ‘d’]
unique_char = set(char_list)
set1 = set(char_list)
set2 = {‘a’, ‘e’, ‘i’}
print( set.difference(set1,set2) )
print( set.difference(set2,set1) )set([‘c’, ‘b’, ‘d’])
set([‘i’, ‘e’])