Python 我可以在string.format方法中使用for循环吗?

Python 我可以在string.format方法中使用for循环吗?,python,Python,我正在尝试将列表写入文件。当我使用以下代码时,它会给我一个错误: with open('list.txt', 'w') as fref : fref.writelines('{}\n'.format(item for item in item_list)) 但当我将代码修改为: with open('list.txt', 'w') as fref : for item in item_list : fref.writeli

我正在尝试将列表写入文件。当我使用以下代码时,它会给我一个错误:

    with open('list.txt', 'w') as fref :
        fref.writelines('{}\n'.format(item for item in item_list))
但当我将代码修改为:

    with open('list.txt', 'w') as fref :
        for item in item_list :
            fref.writelines('{}\n'.format(item))

当我使用%格式化字符串时:

    with open('list.txt', 'w') as fref :
        fref.writelines('%s\n' % item for item in item_list)
它很好用。我不明白为什么format方法中的for循环会失败?

将open('list.txt','w')作为fref:
fref.writelines(“%s\n”%item\u列表中的item对应的item)
可理解为(注意括号):

以open('list.txt',w')作为fref的
:
fref.writelines((“%s\n”%item)用于项列表中的项)
传递
file.writelines
一个生成器表达式,其中每个项都是一个格式化字符串

而:

以open('list.txt',w')作为fref的
:
fref.writelines(“{}\n.”格式(项列表中的项对应项))
创建参数的生成器表达式,该表达式将发送1次到
str.format
方法

相反,创建一个生成器表达式,为
项目列表中的每个项目调用
str.format

以open('list.txt',w')作为fref的
:
fref.writelines(“{}\n.”项列表中项的格式(项)

现在,
file.writelines
接收字符串的生成器表达式作为参数。

{}
是一种基于位置的格式。不能为一个位置提供多个字符串。如果你检查第三个。它与第二个相同,只是将多行传递给
writelines
函数。后两个函数的等效格式表达式是
'{}\n'。项列表中项的格式(项)
。注意在生成器表达式中应用的格式,而不是相反。