将值从列表传递到听写()Python

2024-10-01 04:45:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有3个值的列表。我希望我的循环能够遍历每个列表值,并在听写(),它只是为列表中的每个值输出相同的值。我知道这是在我的for循环中发生的,但不是对列表中的每个项使用相同的值(使用a.json中的当前值和以前的值来用于b.json和c.json),而是希望这些项使用它们自己相应的值。我添加了以下代码:

def readFileIntoDict(pathOfFile):
    fo = open(pathOfFile, "rw+")
    linesOfFiles = fo.readlines()
    dataInFile = {}
    for line in linesOfFiles:
        jsonD = json.loads(line)
        dataInFile[jsonD['File Name']] = jsonD['File Size']
    return dataInFile

jsonDataprevFile = readFileIntoDict('dates/2018-01-01.json')
jsonDatacurrFile = readFileIntoDict('dates/2018-01-02.json')
list1 = jsonDataprevFile.keys()
list2 = jsonDatacurrFile.keys()
names_in_both = set(list1).intersection(list2)

# At this point it loops through 3 times 
file_names = ['a.json', 'b.json', 'c.json']


for fileNames in file_names:
    if fileNames in names_in_both:

         # Get the key a.json from file_name
         print(compare(jsonDataprevFile.get(file_names[0]), jsonDatacurrFile.get(file_names[0])))

Tags: injson列表fornameslinefilefo
2条回答

如果我正确地理解了您想要做的事情,并假设compare()是在代码的其他地方定义的

for file_name in file_names:
    if file_name in names_in_both:
        # Get the key file_name from both json objects
        print(compare(jsonDataprevFile.get(file_name), jsonDatacurrFile.get(file_name)))

另外,请注意readFileIntoDict()函数看起来有点奇怪-如果输入的json文件确实是有效的json,则不应逐行读取/解析。你能上传示例输入json文件吗?你知道吗

您正在file_names上迭代,但不更改值: 把file_names[0]改成file_name

for file_name in file_names:
    if file_name in names_in_both:

         # Get the key a.json from file_name
         print(compare(jsonDataprevFile.get(file_name), jsonDatacurrFile.get(file_name)))

相关问题 更多 >