我正在尝试从标题列表生成一个dict,这些标题将“数据列”关联到同一个实验。例如,我想转:
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]覆盖为空dict。
答案 0 :(得分:1)
您的循环正在覆盖此重要变量并将其设置为空字典:
cols[ run_number ] = {}
这意味着它通过" A _"各种数字的字符串,然后当它们出现在" B _"字符串,它会覆盖它已经为" A _"创建的所有run_number
个键。字符串。
您应该尝试以下内容:
if run_number not in cols:
cols[ run_number ] = {}
或者,您可以尝试使用defaultdict
答案 1 :(得分:1)
您应该更改为以下代码行:
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
答案 2 :(得分:1)
首先,您可以使用enumerate()
让Python自动跟踪计数。其次,正如其他人所说,你用新的字典键覆盖你的字典键,而不是添加到现有的字典中。
以下内容适合您的情况:
cols = {}
for col, header in enumerate(headers):
typ, _, key = header.partition('_')
if key not in cols:
cols[key] = {}
cols[key][typ] = col
根据您的数据,cols
为:
{'1': {'A': 0, 'B': 3}, '2': {'A': 1, 'B': 4}, '3': {'A': 2, 'B': 5}}
答案 3 :(得分:0)
因为" run_number"变量重复,每次循环并重复时,用任何空字典覆盖它。
以下是实现目标的方法。
def answer():
headers = ["A_1","A_2","A_3","B_1","B_2","B_3"]
cols = {}
cols[1] = {}
cols[2] = {}
cols[3] = {}
for header in headers:
cols[int(header[-1:])][str(header[:-1])] = headers.index(header)
return cols
print answer()