簡體   English   中英

匹配字典中的鍵並創建具有關聯值的列表

[英]matching keys from dictionary and create lists with associated values

我是 python 的新手,我遇到了問題。 基本上我有兩個字典,以深度為鍵,以相應的 pH/H2 濃度為值。

現在我想創建兩個新列表,其中包含從兩個字典中獲取的值的 pH 值和 H2 值。 當字典 1 中的深度等於字典 2 中的 depth1 + 6000 時,我只想取 pH 和 H2 的值。例如,深度 1 = 4000 如果滿足此條件,那么深度 2 將是 4000+6000=10000 然后對應的值的 pH 值和 H2 將被放入新列表中。

由於我是 python 的菜鳥,我不知道從哪里開始。 我試過這樣的事情:

   """Aligning of profile data"""
#fill in height of cathode for both profiles
Dept_H2 = 36000
Depth_pH = 42000
#calculate Depth difference
D_diff = Depth_pH - Depth_H2
print(D_diff)
#create dictionaries for pH and H2
H2_M = (Input2['concentration (mol/L)'].to_list())
Depth_H2 = (Input2['Depth H2'].to_list())
pH_dict = dict(zip(Average_depth, Average_pH))
H2_dict = dict(zip(Depth_H2, H2_M))
print(pH_dict)
print(H2_dict)

#create new lists for pH and H2 concentration values
pH = []
H2_con = []

for keys in pH_dict.keys():
    print(keys)
    for base in range(0, len(pH_dict[keys])):
        if keys in H2_dict == (pH_dict.keys() + D_diff):
            pH.append(pH_dict.values())
            H2_con.append(H2_dict.values())                

運行此程序時,我收到以下錯誤:

Traceback (most recent call last):
  File, line 42, in <module>
    for base in range(0, len(pH_dict[keys])):
TypeError: object of type 'numpy.float64' has no len()

但是,即使沒有這個錯誤,我認為這也行不通。 任何關於我應該做什么的提示將不勝感激

pH = []
H2_con = []
for pH_depth, pH_val in pH_dict.items():
    possible_match = H2_dict.get(pH_depth + D_diff)
    if possible_match is not None:
        pH.append(pH_val)    
        H2_con.append(possible_match)

我們遍歷pH_dict的鍵和值,並在H2_dict中為pH_dict中的每個深度尋找所需的匹配。 字典的.get方法將第一個參數作為鍵,如果存在則返回對應的值; 否則,返回None (或第二個參數,如果提供)。 然后我們檢查是否存在和 append。

如果您有 3.8+,您可以使用walrus運算符而不是單獨初始化和檢查possible_match

...
for pH_depth, pH_val in pH_dict.items():
    if possible_match := H2_dict.get(pH_depth + D_diff):
        ...

您也可以使用 go 進行列表理解,但 2 個列表讓我不要:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM