python 字典的減法


da = [
    {"a": 231, "b": 456},
    {"a": 423, "b": 980},
    {"a": 846, "b": 1960},
    {}
]
lst = []
for i in range(len(da) - 1):  # 0 1
    value1 = list(da[i].values())
    value2 = list(da[i + 1].values())
    if value1 and value2:
        for j in range(len(value1)):
            lst.append(value1[j] - value2[j])
print(lst)
##########結果
[-192, -524, -423, -980]
da = [
    {"a": 231, "b": 456},
    {"a": 423, "b": 980},
    {"a": 846, "b": 1960},
    {}
]
lst = []
for i in range(len(da) - 1):  # 0 1
    value1 = list(da[i].values())
    value2 = list(da[i + 1].values())
    if value1 and value2:
        v_lst = []
        for j in range(len(value1)):
            v_lst.append(value1[j] - value2[j])
        lst.append(v_lst)
print(lst)
#############結果
[[-192, -524], [-423, -980]]
lst = []
for i in range(len(da) - 1):  # 0 1
    value1 = list(da[i].values())
    value2 = list(da[i + 1].values())
    v_lst = []
    if not value1:
        lst.append(v_lst)
    elif not value2:
        lst.append(v_lst)
    elif value1 and value2:
        for j in range(len(value1)):
            v_lst.append(value1[j] - value2[j])
        lst.append(v_lst)
print(lst)
################結果
[[], [-192, -524], [], [], []]

這種稍微麻煩一點 需要給每個字典的外層在加一層列表好用索引來

lis = [
    [
        {
            '應收賬款': 2154.00,
            '存貨': 4308.00,

        }
    ],
    [
        {
            '應收賬款': 308.00,
            '存貨':4308.00,
        }
    ],

]
this_month = []

for m in range(1):
    for base_dict, sub_dict in zip(lis[m], lis[m + 1]):
        this_month.append({k: v - sub_dict.get(k, 0) for k, v in base_dict.items()})
print(this_month)

那個滿足就用那個吧,能實現功能就行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM