在我的案例中,我应该使用字典或列表?

时间:2018-01-17 07:15:41

标签: python list dictionary

我有一个文本文件,用于存储图像路径及其标签路径,例如

/JPEGImages/1.jpg /Class/1_label.png
/JPEGImages/2.jpg /Class/2_label.png
/JPEGImages/3.jpg /Class/3_label.png
/JPEGImages/4.jpg /Class/4_label.png
...
/JPEGImages/10000.jpg /Class/10000_label.png

在我的任务中,我将读取文本文件并存储在字典/列表/数组中,以便在单个循环中轻松访问

for i in range 10001
   print ('image path', ...[i])
   print ('label path', ...[i])

我应该使用什么类型的数据?这是我当前的代码,但它只保存最后一个路径

with open('files.txt', 'r') as f:
    for line in f:
        line = line.strip()
        img, gt = line.split()
        img_path = data_dir + img
        gt_path =  data_dir + gt
        img_gt_path_dict["img_path"]=img_path
        img_gt_path_dict["gt_path"] = gt_path
for i in range (10001):
  print (img_gt_path_dict["img_path"][i])
  print (img_gt_path_dict["gt_path"][i])

3 个答案:

答案 0 :(得分:2)

您可以使用元组列表来存储数据。

<强>实施例

res = []
with open('files.txt', 'r') as f:
    for line in f:
        line = line.strip()
        img, gt = line.split()
        img_path = data_dir + img
        gt_path =  data_dir + gt
        res.append((img_path, gt_path))

for i,v in res:
  print("Image Path {0}".format(i))
  print("label  Path {0}".format(v))

使用字典根据评论中的要求

res = {}
c = 0
with open('files.txt', 'r') as f:
    for line in f:
        line = line.strip()
        img, gt = line.split()
        img_path = data_dir + img
        gt_path =  data_dir + gt
        res[c] = {"img_path": img_path, "gt_path": gt_path}
        c += 1

print res

答案 1 :(得分:0)

而不是:

img_gt_path_dict["img_path"]=img_path
img_gt_path_dict["gt_path"] = gt_path

像这样使用:

img_gt_path_dict[img_path]=img_path
img_gt_path_dict[gt_path] = gt_path

因为在dict中你不能复制key.Thats为什么它只存储最后一个值。  因此,您可以在列表中使用list而不是dict或完整的image_path和gt_path存储并输入dict。     要么 像这样

img_path_list = []
gt_path_list = []
with open('files.txt', 'r') as f:
for line in f:
    line = line.strip()
    img, gt = line.split()
    img_path = data_dir + img
    gt_path =  data_dir + gt
    img_path_list.append(img_path)
    gt_path_list.append(gt_path)
img_gt_path_dict["img_path"]=img_path_list
img_gt_path_dict["gt_path"] = gt_path_list
print (img_gt_path_dict["img_path"])
print (img_gt_path_dict["gt_path"])

答案 2 :(得分:0)

简单的解决方案是创建一个列表字典:

paths = {}
paths['img_path'] = []
paths['gt_path'] = []

现在修改您的代码如下

paths = {}
paths['img_path'] = []
paths['gt_path'] = []
with open('file', 'r') as f:        
    for line in f:
        line = line.strip()
        img, gt = line.split()
        paths['img_path'].append(img)
        paths['gt_path'].append(gt)
    l=len(paths['gt_path']) #length of the list
    for i in range(l):
        print "img_path: "+paths['img_path'][i]
        print "gt_path: "+paths['gt_path'][i]