ibeautiful
2021-08-24 16:25:59
這部分課程我不明白這段代碼做了什么:for file in os.listdir(path): if(os.path.isfile(os.path.join(path,file)) and select in file): temp = scipy.io.loadmat(os.path.join(path,file)) temp = {k:v for k, v in temp.items() if k[0] != '_'} for i in range(len(temp[patch_type+"_patches"])): self.tensors.append(temp[patch_type+"_patches"][i]) self.labels.append(temp[patch_type+"_labels"][0][i])self.tensors = np.array(self.tensors)self.labels = np.array(self.labels)尤其是這一行:temp = {k:v for k, v in temp.items() if k[0] != '_'}全班如下:class Datasets(Dataset): def __init__(self,path,train,transform=None): if(train): select ="Training" patch_type = "train" else: select = "Testing" patch_type = "testing" self.tensors = [] self.labels = [] self.transform = transform for file in os.listdir(path): if(os.path.isfile(os.path.join(path,file)) and select in file): temp = scipy.io.loadmat(os.path.join(path,file)) temp = {k:v for k, v in temp.items() if k[0] != '_'} for i in range(len(temp[patch_type+"_patches"])): self.tensors.append(temp[patch_type+"_patches"][i]) self.labels.append(temp[patch_type+"_labels"][0][i]) self.tensors = np.array(self.tensors) self.labels = np.array(self.labels) def __len__(self): try: if len(self.tensors) != len(self.labels): raise Exception("Lengths of the tensor and labels list are not the same") except Exception as e: print(e.args[0]) return len(self.tensors) def __getitem__(self,idx): sample = (self.tensors[idx],self.labels[idx]) # print(self.labels) sample = (torch.from_numpy(self.tensors[idx]),torch.from_numpy(np.array(self.labels[idx])).long()) return sample #tuple containing the image patch and its corresponding label
2 回答

鳳凰求蠱
TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是一個(gè)字典理解;在這種特殊情況下,它dict從現(xiàn)有的 dict創(chuàng)建一個(gè)新的temp,但僅適用于鍵k不以下劃線(xiàn)開(kāi)頭的項(xiàng)目。該檢查由if ...零件執(zhí)行。
它相當(dāng)于
new = {}
for k, v in temp.items():
if key[0] != '_':
new[k] = value
temp = new
或者,略有不同:
new = {}
for key, value in temp.items():
if not key.startswith('_'):
new[key] = value
temp = new
您可以看到它作為單行看起來(lái)更好一些,因?yàn)樗苊饬伺R時(shí) dict (new; 在幕后,它仍然創(chuàng)建了一個(gè)無(wú)名的臨時(shí) dict )。
添加回答
舉報(bào)
0/150
提交
取消