用理解创建字典?

iGw*_*wok 1 python list-comprehension python-3.x

我正在尝试创建一个通过某种条件的目录字典.将每个目录设置为一个值并且每个键从1开始编号是很重要的.

我在这里写了一些东西就是这样,但我想知道是否有更好的方法来做到这一点?

dict(enumerate(sorted([x for x in os.listdir("T:\\") if certain_condition(x)]), start=1))
Run Code Online (Sandbox Code Playgroud)

结果:

{1: 'folderA', 2: 'folderB', 3: 'folderC', 4: 'folderD', 5: 'folderE', 6: 'folderF'}
Run Code Online (Sandbox Code Playgroud)

非常感谢

Mar*_*ers 6

只需使用列表:

[None] + sorted([x for x in os.listdir("T:\\") if certain_condition(x)]
Run Code Online (Sandbox Code Playgroud)

您可以按索引访问每个值,从1开始.

如果你的键不仅仅是顺序整数和/或你需要在不改变索引的情况下从中删除项目,那么dict理解也会起作用:

{'A{}'.format(i + 1): v for i, v in enumerate(sorted(x for x in os.listdir("T:\\") if certain_condition(x)))}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用itertools.count()对象为您提供计数器:

from itertools import count
index = count(1)

{'A{}'.format(next(index)): v for v in sorted(os.listdir("T:\\") if certain_condition(v)}
Run Code Online (Sandbox Code Playgroud)