是python的新版本。我想使用列表理解来显示两个骰子的可能性。我得到了输出。但是,当y达到6(y == 6)时是否可以打印新行?
我的编码:
d1=(1,2,3,4,5,6)
d2=(1,2,3,4,5,6)
print([(x,y) for x in d1 for y in d2])
我的输出:
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]
我的期望输出:
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6),
(2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6),
(3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6),
(4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6),
(6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]
打印具有可选参数end
通常这是一个新行,但是您可以对其进行修改,以使其成为空格或您想要的任何内容。您可以使用它来重新创建所需的输出:
d1=(1,2,3,4,5,6)
d2=(1,2,3,4,5,6)
# this is bad style and should be avoided because of side effects (see comments)
([print((x,y), end='\n' if y==len(d2) else ' ') for x in d1 for y in d2])
更好的无副作用:
for tup in [(x,y) for x in d1 for y in d2]:
print(tup, end='\n' if tup[1]==len(d2) else ' ')
输出:
(1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6)
(2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6)
(3, 1) (3, 2) (3, 3) (3, 4) (3, 5) (3, 6)
(4, 1) (4, 2) (4, 3) (4, 4) (4, 5) (4, 6)
(5, 1) (5, 2) (5, 3) (5, 4) (5, 5) (5, 6)
(6, 1) (6, 2) (6, 3) (6, 4) (6, 5) (6, 6)
而且,如果您真的想要一个真实的列表输出(带有所有特殊字符(“,”,“ [”,“]”),那么您还可以做更多的工作:
def print_nice_list(d1,d2):
print("[",end="")
for tup in [(x,y) for x in d1 for y in d2]:
end = ", "
if tup[1] == len(d2) and tup[0]==len(d1):
end = "]"
elif tup[1] == len(d2):
end = ",\n"
print(tup, end=end )
print_nice_list(d1,d2)
输出:
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6),
(2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6),
(3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6),
(4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6),
(6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]
编辑:根据评论重新设计答案。
如果仅用于可视化,则应使用pprint
:
>>> import pprint
>>> lst = [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]
>>> pprint.pprint(lst, compact=True, width=50)
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6),
(2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6),
(3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6),
(4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6),
(6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]