9:09 2019/1/10/週四
//enumerate()函數的的初步試用。
li=[{"name":"蘋果","price":"10"},{"name":"西瓜","price":"20"},{"name":"橘子","price":"30"}]
for i ,k in enumerate(li):
print("序號:{}\t名稱:{}\t價格:{}".format(i,k['name'],k['price']))
//集合:(是可變的數據類型)但是裏面的元素是不可變的,是無序不重複。裏面沒有重複的元素,所以集合裏面的東西必須是,不可變的!
//集合裏面的增加刪除:
增加:利用add和update。
set1={"蘋果","西瓜","橘子","辣條"}
set1.add("蘋果")
print(set1)
set1.update("adc")
print(set1)
在集合中增加元素,如果重複則不改變,集合中有自動去重複的功能.
//刪除:
set1.pop()//且有返回值。(其中是隨機刪除)
print(set1)
//清空
set1.clear()
print(set1)
//集合中沒有改,只有增刪查
//交集:
2個集合中找到相同的子集合,有用&:
set1={1,2,3,4,5,6}
set2={4,5,6,7,8,9}
print(set1&set2)
結果:{4, 5, 6}
//也可以利用set1.intersection(set2)找到2個集合中的公共子集合:
print(set1.intersection(set2))
//並集:
set1={1,2,3,4,5,6}
set2={4,5,6,7,8,9}
print(set1|set2)
print(set1.union(set2))//2個語句執行結果一樣的。
//反交集
set1={1,2,3,4,5,6}
set2={4,5,6,7,8,9}
print(set1-set2)//set1-set2是set1相比較set2獨有的。
結果:{1, 2, 3}
//把列表裏面的元素轉換成集合(去重複)
set1=[1,2,2,22,3,4,55,55,55,66,6,6,6]
print(set1)
print(set(set1))
結果:
[1, 2, 2, 22, 3, 4, 55, 55, 55, 66, 6, 6, 6]
{1, 2, 3, 4, 66, 6, 22, 55}
//把集合中的元素轉換成列表:
print(list(set(set1)))
[1, 2, 3, 4, 66, 6, 22, 55]
//通過frozenset()函數把可變的轉換成不可變動的數據類型。
//20:33 2019/1/10/週四
//刪除字典中關鍵字帶k的key和value:
dic={"k1":"a1","k2":"a2","k3":"a3","m4":"a4"}
for i in dic:
print(i)
l=[]
for i in dic :
if "k" in i:
l.append(i)
for i in l :
del dic[i]
print(dic)
//面試坑:()
tu1=(1)
tu2=(1,)
print(tu1,type(tu1))
print(tu2,type(tu2))
結果:1 <class 'int'>
(1,) <class 'tuple'>
tu1=({1})
tu2=({1},)
print(tu1,type(tu1))
print(tu2,type(tu2))
結果:
{1} <class 'set'>
({1},) <class 'tuple'>
總結:如果元組裏面只有一個,那個元組裏面的東西該是什麼就是什麼,如果元組裏面有2個以上那麼就是元組類型的數據。