python中带变量的新行

时间:2016-04-21 21:07:55

标签: python python-3.x newline combinations line-breaks

当我在"\n"函数中使用print时,它会在以下代码中给出语法错误

from itertools import combinations
a=[comb for comb in combinations(range(1,96+1),7) if sum(comb) == 42]
print (a "\n")

有没有办法在每个组合中添加新行?

4 个答案:

答案 0 :(得分:7)

The print function already adds a newline for you, so if you just want to print followed by a newline, do (parens mandatory since this is Python 3):

print(a)

If the goal is to print the elements of a each separated by newlines, you can either loop explicitly:

for x in a:
    print(x)

or abuse star unpacking to do it as a single statement, using sep to split outputs to different lines:

print(*a, sep="\n")

If you want a blank line between outputs, not just a line break, add end="\n\n" to the first two, or change sep to sep="\n\n" for the final option.

答案 1 :(得分:1)

两种可能性:

print "%s\n" %a
print a, "\n"

答案 2 :(得分:0)

这对你有用:

我在我的例子中使用1,2 ... 6和使用7的组合总和的2个长度元组。

from itertools import combinations
a=["{0}\n".format(comb) for comb in combinations(range(1,7),2) if sum(comb) == 7]

print(a)
for thing in a:
    print(thing)

输出

['(1, 6)\n', '(2, 5)\n', '(3, 4)\n']
(1, 6)

(2, 5)

(3, 4)

答案 3 :(得分:0)

过去对我来说,像print(“ \ n”,a)这样的东西很有效。