gpt4 book ai didi

Python 有条件地将键添加到字典中

转载 作者:行者123 更新时间:2023-11-30 23:09:40 25 4
gpt4 key购买 nike

我正在尝试从标题列表中生成一个字典,将数据列“关联”到同一实验。比如我想转:

headers = ["A_1","A_2","A_3","B_1","B_2","B_3"]

进入

cols = { 1 : {'A' : 0, 'B' : 3}, 2: {'A' : 1, 'B' : 5} ... }

我的代码如下:

cols = {}
headers = ["A_1","A_2","A_3","B_1","B_2","B_3"]

col_number = 0
for header in headers:
run_number = header[-1:]
cols[ run_number ] = {}

if "A_" in header:
cols[ run_number ][ 'A' ] = col_number
if "B_" in header:
cols[ run_number ][ 'B' ] = col_number

col_number += 1
print cols

这仅输出最后的“B”列:

{'1': {'B':3}, '2':{'B':5}... }

但是,如果我在命令 shell 上尝试一个简单的实验,这种表示法似乎效果很好......

cols = {}
cols[1] = {}
cols[1]['A'] = 1
cols[1]['B'] = 2
print cols

>> {'1' : {'A':1,'B':2} }

为什么?

编辑:我想只是需要另一双眼睛。问题是循环中的这一行...

    cols[ run_number ] = {}

每次到达预先存在的 run_number 中的列时,它都会将 cols[ run_number ] 覆盖为空字典。

最佳答案

您应该更改为以下代码行:

 if run_number not in cols:
cols[ run_number ] = {}

我测试过,以下代码有效:

for header in headers:
run_number = header[-1:]
if run_number not in cols:
cols[ run_number ] = {}
if "A_" in header:
cols[ run_number ][ 'A' ] = col_number
if "B_" in header:
cols[ run_number ][ 'B' ] = col_number
col_number += 1

关于Python 有条件地将键添加到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com