1. 程式人生 > 其它 >字典,列表,字串,集合操作

字典,列表,字串,集合操作

字典

update

#update方法可以利用一個字典更新另一個字典,提供的字典中的項會被新增到舊的字典中,如果有相同的鍵則會被覆蓋
d = {'Tom':8777,'Jack':8888,'Fly':6666}
a = {'Tom':110,'Test':119}
d.update(a)
print(d)   #the result:{'Fly': 6666, 'Test': 119, 'Jack': 8888, 'Tom': 110}

  pop和clear刪除字典中的值

#pop方法用於獲得對應與給定的鍵值,然後將這個鍵值從字典中移除

d = {'Tom':8777,'Jack':8888,'Fly':6666}
v = d.pop('Tom')
print(v)  # 8777

clear清除字典中所有的項,返回None(無返回值)
d = {'name':"tom"}
d.clear()
print(d)  # the result: {}
fromkeys,get,setdefault,for獲取字典中的值
# fromkeys方法使用給定的鍵建立新的字典,每個鍵都對應一個預設的值None
print({}.fromkeys(['name','age']))   #the result:{'age': None, 'name': None}

#  get方法訪問字典項,如果試圖訪問字典中不存在的項時不會報錯僅會      返回:None
d = {'Tom':8777,'Jack':8888,'Fly':6666}
print(d.get('Tom'))                              #the result :     8777

# setdefault方法在某種程度上類似於get方法,能夠獲得與給定鍵相關聯的值,除此之外,setdefault還能在字典中不含有給定鍵的情況下設定相應的鍵值
d = {'Tom':8777,'Jack':8888,'Fly':6666}
d.setdefault('Tom')                           #the result : 8777
print(d.setdefault('Test'))                  #the result : None
print(d)                                      #{'Fly': 6666, 'Jack': 8888, 'Tom': 8777, 'Test': None}

# for迴圈獲取字典中的值得三種方法:
d = {'Tom':8777,'Jack':8888,'Fly':6666}
for k,v in d.items():
    print(k,v)     #  Tom 8777  Jack 8888   Fly 6666
for k in d.values():
    print(k)     #  # 8777   8888  6666  
for k in d.keys():
    print(k)   # Tom  Jack Fly

  

 dict(zip)將兩個列表組合成字典

#將兩個列表組合成字典
keys = ['a', 'b']
values = [1, 2]
print(dict(zip(keys,values)))    # {'a': 1, 'b': 2} 

  

列表

增加資料:append,extend,insert

# 1. append用於在列表末尾追加新的物件
a = [1,2,3]
a.append(4)                          #the result : [1, 2, 3, 4]
​
# 2. extend方法可以在列表的末尾一次性追加另一個序列中的多個值
a = [1,2,3]
b = [4,5,6]
a.extend(b)                          #the result :[1, 2, 3, 4, 5, 6]
​
# 3. insert方法用於將物件插入到列表中
a = [1,2,3]
a.insert(0,'aa')            #the result : ['aa', 1, 2, 3]
​

  

刪除資料:pop,remove

# 1.pop方法會移除列表中的一個元素(預設是最後一個),並且返回該元素的值
a = [1,2,3]
a.pop()                             #the result : [1, 2]
a.pop(0)
​
# 2.remove方法用於移除列表中某個值的第一個匹配項
a = ['aa','bb','cc','aa']
a.remove('aa')                      #the result : ['bb', 'cc', 'aa']

  

查詢資料:index,enumerate

#1. index函式用於從列表中找出某個值第一個匹配項的索引位置
a = [1,2,3,1]
print(a.index(1))                   #the result : 0
​
# 2. enumerate 使用
li = [11,22,33,44,55,66]
for k,v in enumerate(li, 1):  # 1.代表 k 從哪個數字開始
    print(k,v)
'''
1 11
2 22
3 33
'''

  

其他:sort,count,split,reverse

# 1.sort方法用於在原位置對列表進行排序,意味著改變原來的列表,讓其中的元素按一定順序排列
a = ['a','b','c',1,2,3]
a.sort()                           #the result :[1, 2, 3, 'a', 'b', 'c']
​
# 2. count方法統計某個元素在列表中出現的次數
a = ['aa','bb','cc','aa','aa']
print(a.count('aa'))                 #the result : 3
​
# 3.切片
name = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
name[1:6:2]     # [起始位置:終止位置:步長] 每隔 2 個元素才取出一個 ['b', 'd', 'f']
​
# 4.reverse方法將列表中的元素反向存放
a = ['a','b','c']
a.reverse()                         #the result : ['c', 'b', 'a']

  


字串

1).find方法

  • 作用:find方法可以在一個較長的字串中查詢子串,他返回子串所在位置的最左端索引,如果沒有找到則返回-1

a = 'abcdefghijk'
print(a.find('abc'))                 #the result : 0
print(a.find('abc',10,100))   #the result : 11  指定查詢的起始和結束查詢位置

2).join方法

  • 作用:join方法是非常重要的字串方法,他是split方法的逆方法,用來連線序列中的元素,並且需要被連線的元素都必須是字串。

    a = ['1','2','3']
    print('+'.join(a))         #the result : 1+2+3

3).strip方法

# (1)rstrip()
刪除字串末尾的空格或指定字元。

截掉字串左邊的空格或指定字元。
print("   test   test    ".lstrip())      #test   test    
# (3)strip
strip 方法返回去除首位空格(不包括內部)的字串
print("   test   test    ".strip())    #the result :“test   test”

  

4).replace方法

  • 作用 :replace方法返回某字串所有匹配項均被替換之後得到字串

print("This is a test".replace('is','is_test'))     #the result : This_test is_test a test

5).split

  • 作用:用來將字串分割成序列

    print('1+2+3+4'.split('+'))  #the result : ['1', '2', '3', '4']
    

     

6).字串格式化



# 6.1 使用百分號(%)字串格式化
num = 100
print("%d to hex is %x" %(num, num)) #100 to hex is 64
print("%d to hex is %#x" %(num, num)) #100 to hex is 0x64


# 6.2 使用format字串格式化
#1. 位置引數
print("{0} is {1} years old".format("tom", 28)) #tom is 28 years old
print("{} is {} years old".format("tom", 28)) #tom is 28 years old
print("Hi, {0}! {0} is {1} years old".format("tom", 28)) #Hi, tom! tom is 28 years old

#2. 關鍵字引數

print("{name} is {age} years old".format(name = "tom", age = 28)) #tom is 28 years old ​ #3. 下標引數 li = ["tom", 28] print("{0[0]} is {0[1]} years old".format(li)) #tom is 28 years old

  


4.集合

list_1 = [1,2,3,4,5,1,2]

list_2 = [4,5,6,7,8]

(1).去重(去除list_1中重複元素1,2) set

list_1 = set(list_1)    #去重: {1, 2, 3, 4, 5}
print(list_1)
list_2 = set([4,5,6,7,8])  

(2).交集 (在list_1和list_2中都有的元素) intersection

print(list_1.intersection(list_2))     # 交集: {4, 5}
​
print(list_1 & list_2)    #交集    {4, 5}

  

(3).並集(在list_1和list_2中的元素全部打印出來,重複元素僅列印一次) union

print(list_1.union(list_2))   #並集: {1, 2, 3, 4, 5, 6, 7, 8}
​
print(list_1 | list_2)  #並集:  {1, 2, 3, 4, 5, 6, 7, 8}

  

(4).差集 difference

print(list_1.difference(list_2)) #差集:在list_1中有在list_2中沒有:   {1, 2, 3}
print(list_2.difference(list_1)) #差集:在list_1中有在list_2中沒有:   {8, 6, 7}
​
​
print(list_1 - list_2)  #差集:    {1, 2, 3}
print(list_2 - list_1) #差集:  {8, 6, 7}

  

(5).刪除元素 pop

# 1.刪除集合中任意一個元素不會列印刪除的值
list_1.pop()    #Pop()方法:   無返回值
​
​
# 2.discard刪除集合中的指定元素,如過沒有則返回None
print(list_1.discard("ddd"))  #Discard()方法:   刪除指定的值,沒有返回None

  

(6).在集合中新增元素 add

#在集合中新增一個元素999
list_1.add(999)
print(list_1) #Add()方法:          {1, 2, 3, 4, 5, 999}