7days
数据类型的补充
1,元组
tu1 = ("laonanhai")
tu2 = ("laonanhai")
print(tu1,type(tu1))
print(tu2,type(tu2))
tu1 = (1)
tu2 = (1,)
print(tu1,type(tu1))
print(tu2,type(tu2))
tu1 = ([1,2,3])
tu2 = ([1,2,3],)
print(tu1,type(tu1))
print(tu2,type(tu2))
list
l1 = [111,222,333,444,555]
索引为奇数对应的所有元素全部删除。
方法一:
del l1[1::2]
print(l1)
在循坏一个列表时,最好不要改变列表的大小,会影响你的最终结果。
倒着删除
l1 = [111,222,333,444,555,]
for i in range(len(l1)-1,-1,-1):
if in % 2 == 1:
del l1[i]
print(l1)
dict
dic = dict.fronmkeys("abc",666)
print(dic)
dic = dict.fromkeys([11,22,33],666)
print(dic)
dic = dict.fromkeys([11,22,33],[])
print(dic)
l1 = []
for key in dic:
if "k" in key :
l1.append(key)
print(l1)
for key in l1:
del dic[key]
print(dic)
在循坏dict中,最好不要改变dict的大小,会影响结果或者报错。
数据类型的转换:
str ---> list split
list --->str join
tupple --->list
tu1 = (1,2,3)
l1 = list(tu1)
print(l1)
tu2 = tuple(l1)
print(tu2)
列表的去重
l1 = [11,11,22,33,33,44,[1,2,3,4]]
l2 = list (set(l1))
12.sort()
print(l2)
增:2种方法add 和update
set1.add("太白")
print(set1)
set.update("abc")
set1.update([111,222,333])
print(set1)
删:4种方法remove、pop、clear和del
remove按元素删除
set1.remove("alex")
print(set1)
随机删除,有返回值pop
print(set1.pop())
print(set1)
清空clear
set1.clear()
print(set1)
删除整体 del
del set1
print(set1)
查:一种方法for循坏
无序元素
set1 = {"alex","wusir","barry"}
for i in set1:
print(set1)
交集:
& 和 intersetion
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 & set2)
print(set3)
intersetion
print(set1.intersetion(set2))
并集:
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
| 和 union
print(set1 | set2)
print(set1.union(set2))
差集:
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 - set2) set 1 独有
print(set2.difference(set1)) set 1 独有
反交集:
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
子集:
set1 = {1,2,3,}
set2 = {1,2,3,4,5,6}
print(set1 < set2) True set1 是 set2 的子集
print(set1.issubset (set2)) True set1 是 set2 的子集
超集:
set1 = {1,2,3,}
set2 = {1,2,3,4,5,6}
print(set2 > set1) True set2 是 set1 的超集
print(set2.issubset (set1)) True set2 是 set1 的超集
冻集合:
set1 = frozenset({1,2,3,"alex"})
print(set1,type(set1))
l1 = [1,2,3]
l2 = l1
l2.append(666)
print(l1,l2)
对于赋值运算来说,指向的都是同一个内存地址,一变都变。
浅copy:
l1 = [11,22,33]
l2 = l1.copy()
l1.append(666)
print(l1,id(l1))
print(l2,id(l2))
对于浅copy来说,第一层创建的是新的内存地址,而从第二层开始,指向的都是同一个内存地址,所以,对于第二层以及更深的层数来说,保持
深copy:
import copy
l1 = [11,22,["barry"]]
l2 = copy.deepcopy(l1)
l1[2].append("alex")
print(l1,id(l1[-1]))
print(l2,id(l2[-1]))
深copy 完全独立
l1 = [1,2,3]
l2 = [1,2,3]
l1.append(666)
print(l1,l2)
深copy,两个内存地址
对于切片来说,这是浅copy
l1 = [1,2,3,4,5,6,[11,22]]
l2 = l1[:]
l1.append(666)
print(l1.l2)
l1[-1].appemd(666)
print(l1,l2)