python3 有關字典的一些用法

2021-08-30 10:48:25 字數 1533 閱讀 9596

如:res = (('a', 1), ('a', 2), ('c', 3), ('d', 4))

轉為:

# 組成字典,若重複,則是values值相加

res = (('a', 1), ('a', 2), ('c', 3), ('d', 4))

adict = {}

for i in range(0, len(res)):

if res[i][0] in list(adict.keys()):

adict[res[i][0]] = int(adict[res[i][0]]) + int(res[i][1])

else:

adict[res[i][0]] = int(res[i][1])

print(adict)

結果:

zip函式的用法:   

zip()函式用於將可迭代的物件作為引數,將物件中對應的元素打包成乙個個元組,然後返回由這些元組組成的列表。

如果各個迭代器的元素個數不一致,則返回列表長度與最短的物件相同,利用 * 號操作符,可以將元組解壓為列表。

zip 語法:

zip([iterable, ...])
引數說明:

直接放乙個例子: 

a = ['a', 'b', 'c']

b = [1, 2, 3]

print(list(zip(a, b)))

print(dict(zip(a, b)))

結果:[('a', 1), ('b', 2), ('c', 3)]

pdf_dict = 

sql_dict =

# 兩個字典key值的並集

all_keys = pdf_dict.keys() | sql_dict.keys()

print('k', 'pdf', 'sql')

for k in all_keys:

# 三個判斷,

# 1.若key兩者都存在時 判斷values值是否相等

# 2.key分別存在時,另乙個寫『無』

# 3.須注意在其中可能有0的存在, 在這裡0說明沒有既是『無』

if k in sql_dict.keys() and k in pdf_dict.keys():

if pdf_dict[k] == sql_dict[k]:

continue

print(k, pdf_dict[k], sql_dict[k])

elif k in sql_dict and sql_dict[k] != 0:

print(k, '無', sql_dict[k])

elif pdf_dict[k] != 0:

print(k, pdf_dict[k], '無')

# 結果:

k pdf sql

b 2 4

d 無 7

c 3 無

bpython3 推送 python3一些用法

python3自定義演算法排序 sorted a1,key functools.cmp to key cmp a1是待排序list,cmp為排序函式 numpy a np.vstack x,np.ones len x t a為x引數矩陣,vstack是新增一列1作為偏置項 a,b np.linalg...

python3 的一些筆記

因為使用python越來越頻繁,有一些細節的東西經常用後一段時間沒去用就會忘記,做些簡單的筆記吧。a 0 while 1 a 1 if a 3 0 print aa else print bb continue 後面的全部不執行了 pass 似乎沒影響,cc也會出來 break 直接結束迴圈 pri...

python3 有關getattr 函式的用法

getattr object,name default 返回物件命名屬性的值。name 必須是字串。如果該字串是物件的屬性之一,則返回該屬性的值。例如,getattr x,foobar 等同於x.foobar。如果指定的屬性不存在,且提供了 default 值,則返回它,否則觸發attributee...