将代码简化为字典理解

lok*_*oki 0 python dictionary dictionary-comprehension

在一个目录images 中,图像被命名为 - 1_foo.png2_foo.png14_foo.png等。

图像经过 OCR 处理,文本提取物dict通过以下代码存储在 a中 -

data_dict = {}

for i in os.listdir(images):
    if str(i[1]) != '_':
        k = str(i[:2])  # Get first two characters of image name and use as 'key'
    else:
        k = str(i[:1])  # Get first character of image name and use 'key'
    # Intiates a list for each key and allows storing multiple entries
    data_dict.setdefault(k, [])
    data_dict[k].append(pytesseract.image_to_string(i))
Run Code Online (Sandbox Code Playgroud)

代码按预期执行。
图像的名称中可以有不同的数字,范围从 1 到 99。
这可以简化为dictionary comprehension吗?

Den*_*nis 6

不是。字典推导式中的每次迭代都会为一个键分配一个值;它无法更新现有值列表。字典理解并不总是更好——您编写的代码似乎已经足够好了。虽然也许你可以写

data_dict = {}

for i in os.listdir(images):
    k = i.partition("_")[0]
    image_string = pytesseract.image_to_string(i)
    data_dict.setdefault(k, []).append(image_string)
Run Code Online (Sandbox Code Playgroud)