use*_*753 4 python combinations newline line-breaks python-3.x
当我"\n"在我的print函数中使用时,它在下面的代码中给出了语法错误
from itertools import combinations
a=[comb for comb in combinations(range(1,96+1),7) if sum(comb) == 42]
print (a "\n")
Run Code Online (Sandbox Code Playgroud)
有没有办法在每个组合中添加新行?
该print函数已经为您添加了换行符,因此如果您只想打印后跟换行符,请执行(必须填写,因为这是Python 3):
print(a)
Run Code Online (Sandbox Code Playgroud)
如果目标是打印a由换行符分隔的每个元素,则可以显式循环:
for x in a:
print(x)
Run Code Online (Sandbox Code Playgroud)
或滥用星形解包将其作为单个语句执行,使用sep将输出拆分为不同的行:
print(*a, sep="\n")
Run Code Online (Sandbox Code Playgroud)
如果你想输出之间的空行,而不仅仅是一个断行,加上end="\n\n"前两个,或更改sep到sep="\n\n"了最后一个选项.