创建词典列表

use*_*732 0 python

我有代码生成28个词典的列表.它循环通过28个文件并链接相应字典中每个文件的数据点.为了使我的代码更灵活,我想使用:

tegDics = [dict() for x in range(len(files))]
Run Code Online (Sandbox Code Playgroud)

但是当我运行代码时,前27个字典是空白的,只有最后一个,tegDics [27]有数据.下面是代码,包括我必须使用的笨拙但功能强大的代码生成字典:

x=0
import os
files=os.listdir("DirPath")
os.chdir("DirPath")
tegDics = [{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}] # THIS WORKS!!!
#tegDics = [dict() for x in range(len(files))] - THIS WON'T WORK!!!
allRads=[]
while x<len(tegDics): # now builds dictionaries 
    for line in open(files[x]):
        z=line.split('\t')
        allRads.append(z[2])
        tegDics[x][z[2]]=z[4] # pairs catNo with locNo
    x+=1
Run Code Online (Sandbox Code Playgroud)

有人知道为什么更优雅的代码不起作用.

Kev*_*vin 6

由于你在x列表理解中使用,当你到达while循环时它将不再为零- 它将是len(files)-1相反的.我建议将您使用的变量更改为其他内容.对于您不关心的值,使用单个下划线是传统的.

tegDics = [dict() for _ in range(len(files))]
Run Code Online (Sandbox Code Playgroud)

x完全消除你的使用可能是有用的.python中的习惯是直接迭代序列中的对象,而不是使用计数器变量.你可以这样做:

for tegDic in tegDics:
    #do stuff with tegDic here
Run Code Online (Sandbox Code Playgroud)

虽然这是在你的情况稍微棘手,因为要同时通过迭代tegDicsfiles在同一时间.你可以zip用来做那件事.

import os
files=os.listdir("DirPath")
os.chdir("DirPath")
tegDics = [dict() for _ in range(len(files))]
allRads=[]
for file, tegDic in zip(files,tegDics):
    for line in open(file):
        z=line.split('\t')
        allRads.append(z[2])
        tegDic[z[2]]=z[4] # pairs catNo with locNo
Run Code Online (Sandbox Code Playgroud)