用Python迭代写入文件,在每次迭代中创建一个新字符串

时间:2019-02-18 17:52:16

标签: python

我想我没有找到明显的地方,但是我要感谢指出这一点的人。使用语法已经一个小时了,我很沮丧。

以下是MWE。运行时间不到1秒:

from itertools import product

PARAM_GRID = list(product(
range(64, 68),
range(64, 68),
range(132, 136),
range(132, 136),
))

SCOREFILE = './fake_scores.csv'

def search_distributed():

    for param_ix in range(len(PARAM_GRID)):

        params = PARAM_GRID[param_ix]
        score = 0.9

        with open(SCOREFILE, 'a') as f:
            #NOT MINE, and doesn't do what I want
            #f.write('{",".join(map(str, params + (score,)))}\n')

            #MINE, and still doesn't do what I want.
            paramstr = str(params) 
            scorestr = str(score) 
            f.write("\n".join({paramstr + ' ' + scorestr}))

def main():
    search_distributed()

if __name__ == '__main__':
    main()

包含以下内容的文件代替了它的创建内容:

(64, 64, 132, 132) 0.9(64, 64, 132, 133) 0.9(64, 64, 132, 134) 0.9...

我想要一个包含以下内容的文件:

(64, 64, 132, 132) 0.9
(64, 64, 132, 133) 0.9
(64, 64, 132, 134) 0.9

显然,我需要以某种方式修改join命令。我已经在上面展示了我的尝试。谁能解决这个问题?

1 个答案:

答案 0 :(得分:1)

这是您的代码的一小部分调整,可以解决您的问题:

from itertools import product

PARAM_GRID = list(product(
range(64, 68),
range(64, 68),
range(132, 136),
range(132, 136),
))

SCOREFILE = './fake_scores.csv'

def search_distributed():

    for param_ix in range(len(PARAM_GRID)):

        params = PARAM_GRID[param_ix]
        score = 0.9

        with open(SCOREFILE, 'a') as f:
            #NOT MINE, and doesn't do what I want
            #f.write('{",".join(map(str, params + (score,)))}\n')

            #MINE, and still doesn't do what I want.
            paramstr = str(params) 
            scorestr = str(score) 
            f.write(paramstr + ' ' + scorestr + '\n')

def main():
    search_distributed()

if __name__ == '__main__':
    main()

由于您仅向{paramstr + ' ' + scorestr}方法提供一个元素(join仅是一个字符串,而不是元素列表),因此不会添加任何“ \ n”。您只需要手动将其添加到每一行的末尾即可。