1、add(element) ##给集合添加元素(整体作为元素)
创建集合{}:大括号或者set()函数
集合的特性:去重(所以元素重复不添加)set()函数本质上是一个迭代器(逐个遍历)
fruits = {"apple","banana",'cherry'}
list1 = ["apple",'banana',"cherry"]
fruits1 = set(list1)
print(fruits)
print(fruits1)
#{'banana', 'apple', 'cherry'}
#{'banana', 'apple', 'cherry'}
fruits.add("orange") #add只能添加一个元素
fruits.add("apple")
fruits1.add("orange")
fruits1.add('apple')
print(fruits)
print(fruits1)
#{'apple', 'orange', 'banana', 'cherry'}
#{'apple', 'orange', 'banana', 'cherry'}
fruits.remove('cherry')
fruits1.remove('cherry')
print(fruits)
print(fruits1)
#{'banana', 'orange', 'apple'}
#{'banana', 'orange', 'apple'}
#多个集合还可以像数学一样求交集(使用符号&:读and,例如s=set(1)&set(2))
#多个集合还可以像数学一样求并集(使用符号|:读管道符,例如s=set(1)|set(2))
2、append(object) ##给列表添加元素(可以是列表,字典,元组,集合,字符串等)
创建一个列表[]:中括号定义,列表中的数据用“,”分割。列表是使用最频繁的类型,索引从0开始。
列表的常用操作:list
(1)、增加:
list.append(数据):把数据追加到列的末尾
list.extend(列表):把列表追加到列的末尾
list.insert(索引位置,数据):把数据插入到指定索引位置
(2)、删除:
del list:删除列表,del list[索引位置]:删除索引位置的数据
list.clear:清空列表,list.remve[数据]:删除列表中指定的数据
list.pop():弹出(删除)尾列数据,list.pop(索引位置):弹出(删除)索引位置的数据
(3)、修改:
list[索引位置]=数据:修改指定位置的数据
(4)、统计:
len(list):统计列表的长度,list.count(数据):统计指定数据在列表中出现的次数
range(len(list)):可以结合for循环切片依次从列表取值如:
for i in range(len(list)):
print(list[i])
(5)、排序:
list,sort():升序排列,list.sort(reverse=True):降序排列,list.reverse():反转排列
3、extend(seq) ##用于列尾一次性增加另一个序列中的多个值
将一个可迭代对象中的所有元素,逐个添加到列尾,通常,可迭代对象为list
为字符串时,把每个字符逐个添加到列表末尾,为字典时,只依次添加key到末尾
4、insert(index,obj) ##将对象作为一个整体插入到索引位置
插入到列尾时index:索引位置为len(list),当用[-n]做索引位置时插入后,后边还有n列