6 回答
TA贡献1856条经验 获得超17个赞
您将需要遍历列表并打印每个项目而不是打印列表本身
with open('output.txt', 'w') as f:
for k in ''.join(i) for i in product(ascii_lowercase, repeat = 2):
f.write('{}\n', k)
TA贡献1784条经验 获得超2个赞
把事情简单化。如果您对该输出要做的只是将其逐行写入文件,那么您甚至不需要首先生成列表:
from itertools import product
from string import ascii_lowercase
with open('output.txt', 'w') as f:
for i in product(ascii_lowercase, repeat=2):
f.write(''.join(i) + '\n')
TA贡献1799条经验 获得超6个赞
以下是如何使用上下文管理器:
from itertools import product
from string import ascii_lowercase
with open('output.txt','w') as f:
for i in product(ascii_lowercase, 2)
f.write(''.join(i)+'\n')
TA贡献1820条经验 获得超10个赞
from itertools import product
from string import ascii_lowercase
keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 2)]
for i in range(0,len(keywords),2):
print(f'{keywords[i]} {keywords[i+1]}')
写入文件使用:
with open('out.txt', 'w') as fp:
for i in range(0,len(keywords),2):
fp.write(f'{keywords[i]} {keywords[i+1]}\n')
TA贡献1880条经验 获得超4个赞
尝试这个:
with open('output.txt', 'w') as file:
for string in keywords:
file.write(string + '\n')
TA贡献1811条经验 获得超4个赞
那么你可以print按照你想要的方式,例如:
>>> some_list = [chr(i) for i in range(80,90)]
>>> some_list
['P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']
>>> f = open('somefile.txt', 'w')
>>> print(*some_list, sep='\n', file=f)
>>> f.close()
somefile.txt:
P
Q
R
S
T
U
V
W
X
Y
在您的情况下,它可以是:
keywords = (''.join(i) for i in product(ascii_lowercase, repeat = 2))
with open('output.txt') as f:
print(*keywords, sep='\n', file=f)
添加回答
举报