从列表/数组字典中迭代实例化类的最佳方法是什么?

2024-04-25 16:51:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个包含许多列的文本文件中读取数据集,每列对应一个字典键。因此,每个字典键对应一个数组值。我想在每个索引的基础上为所有键实例化一个类实例下面的示例代码片段很有效,不过我想知道是否有更好的方法来实现这一点(在速度、Python等方面更好)

首先初始化一些示例数据

import numpy as np

ts = np.array([0, 2, 6, 10])
ss = np.array([100, 90, 120, 130])
ns = np.array(['A', 'C', 'G', 'K'])

data = dict(time=ts, size=ss, name=ns)
print(data)

产生以下输出:

{'name': array(['A', 'C', 'G', 'K'],
      dtype='<U1'), 'time': array([ 0,  2,  6, 10]), 'size': array([100,  90, 120, 130])}

然后我创建一个示例类并实例化任意数组的每个索引(因为它们的大小都相同)

class SampleProblem():

    def __init__(self, time, size, name):
        self.time = time
        self.size = size
        self.name = name

res = []
for idx in range(len(data['time'])):
    res.append(SampleProblem(data['time'][idx], data['size'][idx], data['name'][idx]))
# not written as a list comprehension for readability purposes

for idx in range(len(res)):
    print(res[idx].name)

产生以下输出:

A
C
G
K

Tags: 实例nameself示例fordatasize字典
1条回答
网友
1楼 · 发布于 2024-04-25 16:51:56

zip是一种Pythonic替代方法:

res = [SampleProblem(t, s, n)  for t, s, n in \
       zip(data['time'], data['size'], data['name'])]

可能更好的办法是在列表理解之前用zip重新排列字典:

data = dict(enumerate(zip(ts, ss, ns)))
# {0: (0, 100, 'A'), 1: (2, 90, 'C'), 2: (6, 120, 'G'), 3: (10, 130, 'K')}

res = [SampleProblem(*args) for args in  data.values()]

相关问题 更多 >