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

What should I use dictionary or list in my case?

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

/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

在我的任务中,我将读取文本文件并将其存储在 dictionary/list/array 中,以便在单个循环中轻松访问

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])

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

例如:

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

而不是:

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"])

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

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]