numpy 在循环中创建字典

tvmytwxo  于 2023-03-18  发布在  其他
关注(0)|答案(4)|浏览(188)

我想在一个循环中创建一个字典。同时,我想用循环命名字典中的每个元素。

table = {}

elasticity = np.array([[1,2],[3,4]])
elasticity.shape

genders = ['female', 'male']
income = ['i0','i1']

for i in range(len(genders)):
    for j in range(len(income)):
        key = genders[i]+"_"+income[j]
        table = ["key"=elasticity[i,j]]

我知道我有一个错误,在最后一行不知何故“=”是错误的,但我不能修复它。
这是我想要的:

female_i0 = 1
female_i1 = 2

male_i0 = 3
male_i1 = 4
oxiaedzo

oxiaedzo1#

这将为你解决它,问题在于字典的赋值。

import numpy as np

elasticity = np.array([[1,2],[3,4]])
genders = ['female', 'male']
income = ['i0','i1']

table = {}
for i in range(len(genders)):
    for j in range(len(income)):
        key = genders[i]+"_"+income[j]
        table[key] = elasticity[i,j]
print(table)

则输出为:

{'female_i0': 1, 'female_i1': 2, 'male_i0': 3, 'male_i1': 4}
6jjcrrmo

6jjcrrmo2#

从python 3.9开始,你可以使用update操作符:

table = {}

elasticity = np.array([[1,2],[3,4]])
elasticity.shape

genders = ['female', 'male']
income = ['i0','i1']

for i in range(len(genders)):
    for j in range(len(income)):
        key = f"{genders[i]}_{income[j]}"
        table |= { key: elasticity[i,j]}

在这个例子中,我还使用了一个f字符串来生成密钥,这是我不久前做的一个基准测试中最快的选项。

lzfw57am

lzfw57am3#

您还可以使用字典理解在一行中创建字典:

import numpy as np

elasticity = np.array([[1,2],[3,4]])

genders = ['female', 'male']
income = ['i0', 'i1']

table = {f"{gen}_{inc}": elasticity[i, j] for i, gen in enumerate(genders) for j, inc in enumerate(income)}

print(table)

输出:

{'female_i0': 1, 'female_i1': 2, 'male_i0': 3, 'male_i1': 4}
xoshrz7s

xoshrz7s4#

使用单字节理解:

table = {k:v for i, g in enumerate(genders) 
         for k, v in zip(map('_'.join, zip([g] * len(income), income)), elasticity[i])}
print(table)
{'female_i0': 1, 'female_i1': 2, 'male_i0': 3, 'male_i1': 4}

相关问题