我从包含许多列的文本文件中读取数据集,其中每一列对应于一个字典键。因此,每个字典键对应一个数组值。我想在每个索引的基础上为所有键实例化一个类实例。 下面的示例代码片段有效,但我想知道是否有更好的方法来做到这一点(在速度、Pythonic 等方面更好)。
首先我初始化一些示例数据。
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
最佳答案
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()]
关于python - 从列表/数组字典中迭代实例化类的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49129604/