从python字典访问数据

2024-04-29 16:27:07 发布

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

import numpy as np

def unpickle(file):
   import pickle
   with open(file, 'rb') as fo:
   dict = pickle.load(fo, encoding='bytes')
   return dict

 train = []
for j in range (1,6):
train.append(unpickle('/Users/sachalabdullah/Desktop/cifar-10-batches-py/data_batch_'+str(j)))

test = unpickle ("/Users/sachalabdullah/Desktop/cifar-10-batches-py/test_batch”)

我已经加载了cifar10,因为我是python新手,我不知道如何从字典中访问数据。你知道吗

还有一件事让我困惑,我在train中附加了所有五批训练数据。假设我只能访问数据集中的标签和图像,那么如果我访问它,我将从所有五批中获取数据,或者我需要分别访问每批的图像和标签?你知道吗

如果我想从一个矩阵中得到列1和列2,我会做A(:, [1,2]),或者没有什么Matlab等价物?你知道吗


Tags: 数据pyimportasbatchestrainuserspickle
2条回答

要访问字典中的键:

mydict={'mykey':['value1','value2']}

#access mykey from mydict:
mydict['mykey']

要将这些数据正确地加载到dict中,我可以这样做:

def unpickle(file):
   import pickle
   dict={}
   with open(file, 'rb') as fo:
   dict[fo] = pickle.load(fo, encoding='bytes')
   return dict

#how to access the data in your train[j] dict:
[v for v in train[j].values()]

python等效于获取矩阵的前两行:

A=np.matrix([[1, 2, 3], [3, 4, 5], [5, 6, 7]])
A[:,[0,1]]

请记住,对于python,索引从0开始。matlab索引从1开始。你知道吗

首先创建转储文件。你知道吗

file = open('filename', 'r')
obj = file.read()
pickle.dump(obj, open('file.pickle', 'wb'))

那么

with open(file.pickle, 'rb') as fo:
   dict = pickle.load(fo, encoding='bytes')

相关问题 更多 >